Bash中的grep命令
我在Bash中编写了以下函数:Bash中的grep命令,bash,unix,Bash,Unix,我在Bash中编写了以下函数: function findTest { files=`ls $1` for file in ${files[*]}; do if [[ "$file"=="*.tst" ]]; then grep "version: $2" $1/$file if [[ $? -eq 0 ]]; then echo -n $2 grep "result" | cut -d ":" -f2
function findTest {
files=`ls $1`
for file in ${files[*]}; do
if [[ "$file"=="*.tst" ]]; then
grep "version: $2" $1/$file
if [[ $? -eq 0 ]]; then
echo -n $2
grep "result" | cut -d ":" -f2
fi
fi
done
}
出于某种奇怪的原因,grep版本:$2$1/$file声明$1/$file不是文件/目录,但我知道$1包含$file所在的目录地址。在for循环中使用globbing并列出扩展名文件,而不是尝试运行ls并解析其输出,这有什么合理的原因吗
与其尝试运行ls并解析其输出,不如在for循环中使用globbing并列出扩展名的文件:
发布的代码片段存在许多问题 找到了很多
1 function findTest {
2 files=`ls $1`
^––SC2006 Use $(..) instead of legacy `..`.
^––SC2086 Double quote to prevent globbing and word splitting.
3 for file in ${files[*]}; do
4 if [[ "$file"=="*.tst" ]]; then
^––SC2077 You need spaces around the comparison operator.
^––SC2140 The double quotes around this do nothing. Remove or escape them.
5 grep "version: $2" $1/$file
^––SC2086 Double quote to prevent globbing and word splitting.
^––SC2086 Double quote to prevent globbing and word splitting.
6 if [[ $? -eq 0 ]]; then
7 echo -n $2
^––SC2086 Double quote to prevent globbing and word splitting.
8 grep "result" | cut -d ":" -f2
9 fi
10 fi
11 done
12 }
它找不到的东西是这样的,文件不是您试图创建的数组,或者${files[*]}假设它是数组,不如${files[@]}有用,因为带引号或不带引号的*版本不会处理名称中带有空格的文件,等等。发布的代码片段存在许多问题 找到了很多
1 function findTest {
2 files=`ls $1`
^––SC2006 Use $(..) instead of legacy `..`.
^––SC2086 Double quote to prevent globbing and word splitting.
3 for file in ${files[*]}; do
4 if [[ "$file"=="*.tst" ]]; then
^––SC2077 You need spaces around the comparison operator.
^––SC2140 The double quotes around this do nothing. Remove or escape them.
5 grep "version: $2" $1/$file
^––SC2086 Double quote to prevent globbing and word splitting.
^––SC2086 Double quote to prevent globbing and word splitting.
6 if [[ $? -eq 0 ]]; then
7 echo -n $2
^––SC2086 Double quote to prevent globbing and word splitting.
8 grep "result" | cut -d ":" -f2
9 fi
10 fi
11 done
12 }
它找不到的东西是这样的,文件不是您试图创建的数组,或者${files[*]}假设它是数组,不如${files[@]}有用,因为带引号或不带引号的*版本不会处理名称中带有空格的文件,等等。试试grep版本:$2$1/$filefilefiles=`ls$1`没有创建数组。如果$1是一个目录,则需要files=$1或files=$1/*来执行此操作。我会打开set-x,这样您就可以看到它正在运行的命令的扩展版本,也许它没有像您所想的那样扩展。此外,如果您的任何文件名中有空格,那么您在执行此路径时会遇到困难,因为一旦您获得了一个实际数组,您希望在${files[@]}中为文件使用该数组作为循环,以正确处理文件名中的空格等。在中的==周围还需要空格[[测试或您正在测试整个字符串是否为非空,而它显然不是空的。请尝试grep版本:$2$1/$filefiles=`ls$1`没有创建数组。如果$1是一个目录,则需要files=$1或files=$1/*来执行此操作。我会打开set-x,以便您可以看到它正在运行的命令的扩展版本,也许它没有如您所想的那样扩展。Also、 如果您的任何文件名中有空格,那么您在执行此路径时就会遇到问题。一旦您在${files[@]}中获得了一个实际的数组,作为循环,以正确处理文件名中的空格等。您还需要在${files[@]}中的==周围使用空格[[测试或者你正在测试整个字符串是否为非空,而它显然不是空的。还有一个问题:命令grep result没有指定输入文件,因此它将挂起等待终端输入。我非常确定这不是预期的行为,但我也不确定它应该做什么…@GordonDavisson:我认为OP正在尝试中g从grep输出中删除文件名,并且显然不知道bash字符串扩展。还有一个问题:命令grep result没有指定输入文件,因此它将挂起等待终端输入。我很确定这不是预期的行为,但我也不确定它应该做什么…@GordonDavisson:我认为EOP试图从grep输出中删除文件名,并且显然不知道bash字符串扩展。