2017-02-21 33 views
2

我想提出一个剧本,我的学校,我不知道我怎么会检查文件,如果该字符串不是在文件中,做一个代码,但如果是继续,就像这样:虽然文件不包含字符串BASH

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 
+1

所以...你有什么问题 –

回答

4

你可以这样做:

$ if grep "string" file;then echo "found";else echo "not found" 

为了做一个循环:

$ while ! grep "no" file;do echo "not found";sleep 2;done 
$ echo "found" 

但要小心不要进入一个无限循环。字符串或文件必须改变,否则循环没有意义。

以上,如果/当基于命令的返回状态,而不是结果的作品。 如果grep发现文件中的字符串将返回0 =成功= true 如果grep找不到字符串将返回1 =不成功= false

通过使用!我们将“false”恢复为“true”以保持循环运行,因为尽管循环处于某种状态。

一个更传统的while循环将类似于你的代码,但没有无用的使用猫和额外的管道:

$ while [ -z $(grep "no" a.txt) ];do echo "not found";sleep 2;done 
$ echo "found" 
+0

这就是我想,但我?希望它继续打印“找不到”,直到找到字符串。 –

+0

@Python更新 –

+0

@Python更新和解释。是你在找什么...? –

2

如果测试语句是否“串”不file.txt简单:

#!/bin/bash 
if ! grep -q string file.txt; then 
    echo "string not found in file!" 
else 
    echo "string found in file!" 
fi 

-q选项(--quiet--silent)确保输出不被写入到标准输出。

一个简单的while循环测试是一个“串”不file.txt

#!/bin/bash 
while ! grep -q string file.txt; do 
    echo "string not found in file!" 
done 
echo "string found in file!" 

注:知道的可能性while循环可能会导致死循环!

+0

@与我的解决方案有什么不同? –

+1

如果找不到'grep'的'-q'选项,字符串将被打印到标准输出。 –

0

另一种简单的方法是只做到以下几点:

[[ -z $(grep string file.file) ]] && echo "not found" || echo "found" 

&&手段和 - 或执行下面的命令,如果以前是真正

||手段或 - 或执行,如果前面的是

[[ -z $(expansion) ]]手段返回如果扩展输出为

此行是很像一个双重否定,基本上是: “返回如果字符串不在文件中找到。文件;然后回显没有找到如果,或发现如果

例子:

bashPrompt:$ [[ -z $(grep stackOverflow scsi_reservations.sh) ]] && echo "not found" || echo "found" 
not found 
bashPrompt:$ [[ -z $(grep reservations scsi_reservations.sh) ]] && echo "not found" || echo "found" 
found