我正在为我的学校制作脚本,我想知道如何检查文件,如果字符串不在文件中,则执行代码,但如果是,则继续,如下所示:
while [ -z $(cat File.txt | grep "string" ) ] #Checking if file doesn't contain string
do
echo "No matching string!, trying again" #If it doesn't, run this code
done
echo "String matched!" #If it does, run this code
最佳答案
你可以这样做:
$ if grep "string" file;then echo "found";else echo "not found"
做一个循环:
$ while ! grep "no" file;do echo "not found";sleep 2;done
$ echo "found"
但要注意不要进入死循环。必须更改字符串或文件,否则循环没有意义。
上面的 if/while 是根据命令的返回状态而不是结果来工作的。 如果 grep 在文件中找到字符串,将返回 0 = success = true 如果 grep 没有找到字符串将返回 1 = 不成功 = false
通过使用!我们将“false”恢复为“true”以保持循环运行,因为 while 会在某些内容为真时立即循环。
更传统的 while 循环与您的代码类似,但没有无用地使用 cat 和额外的管道:
$ while [ -z $(grep "no" a.txt) ];do echo "not found";sleep 2;done
$ echo "found"
关于bash - 虽然文件不包含字符串 BASH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42377739/