我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码出了什么问题?
我想检查一个文件是否包含一个特定的字符串或不在bash。我使用了这个脚本,但它不起作用:
if [[ 'grep 'SomeString' $File' ]];then
# Some Actions
fi
我的代码出了什么问题?
当前回答
如果您想检查文件是否不包含特定的字符串,您可以按照以下方法进行检查。
if ! grep -q SomeString "$File"; then
Some Actions # SomeString was not found
fi
其他回答
grep -q [PATTERN] [FILE] && echo $?
如果找到模式,则退出状态为0 (true);否则blankstring。
除了告诉你如何做你想做的事情的其他答案之外,我试图解释哪里出了问题(这是你想要的)。
在Bash中,if后面跟着一个命令。如果该命令的退出码为0,则执行then部分,否则执行else部分。
你可以用其他答案中解释的任何命令来做到这一点:然后…;fi
[[是一个内部bash命令,专门用于一些测试,如文件存在性、变量比较。类似地,[是一个外部命令(它通常位于/usr/bin/[),执行大致相同的测试,但需要]作为最终参数,这就是为什么]必须在左侧填充一个空格,而[]则不是这样。
这里你不需要[[nor[]。
另一件事是你引用东西的方式。在bash中,只有一种情况下双引号嵌套,它是"$(命令"参数")"。但是在'grep 'SomeString' $File'中只有一个单词,因为'grep '是一个引用的单位,它与SomeString连接,然后再次与' $File'连接。由于使用了单引号,变量$File甚至没有被它的值替换。正确的方法是grep 'SomeString' "$File"。
if grep -q SomeString "$File"; then
Some Actions # SomeString was found
fi
这里不需要[[]]。直接执行命令即可。添加-q选项时,您不需要显示当它被找到的字符串。
grep命令在退出码中返回0或1,具体取决于 搜索的结果。如果发现了什么,则为0;否则1。
$ echo hello | grep hi ; echo $?
1
$ echo hello | grep he ; echo $?
hello
0
$ echo hello | grep -q he ; echo $?
0
您可以指定命令作为if的条件。如果该命令在其exitcode中返回0,则意味着条件为真;否则错误。
$ if /bin/true; then echo that is true; fi
that is true
$ if /bin/false; then echo that is true; fi
$
如您所见,您在这里直接运行程序。没有附加的[]或[[]]。
如果你想检查字符串是否匹配整行,如果它是一个固定的字符串,你可以这样做
grep -Fxq [String] [filePath]
例子
searchString="Hello World"
file="./test.log"
if grep -Fxq "$searchString" $file
then
echo "String found in $file"
else
echo "String not found in $file"
fi
从男子档案中可以看出:
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by newlines, any of
which is to be matched.
(-F is specified by POSIX.)
-x, --line-regexp
Select only those matches that exactly match the whole line. (-x is specified by
POSIX.)
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero
status if any match is
found, even if an error was detected. Also see the -s or --no-messages
option. (-q is specified by
POSIX.)
if grep -q [string] [filename]
then
[whatever action]
fi
例子
if grep -q 'my cat is in a tree' /tmp/cat.txt
then
mkdir cat
fi