虽然文件不包含字符串 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

您可以做类似:

的事情
$ 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 =成功= true如果GREP找不到字符串将返回1 =不成功= false

使用!我们将" false"恢复为" true"以保持循环运行,因为在某些事物是真的时循环时。

更常规的循环将与您的代码相似,但没有无用的猫和额外的管道:

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

一个简单的if语句测试是否不在 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)确保输出不会写入标准输出。

一个简单的循环测试是"字符串",不在 file.txt中:

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

注意:请注意,while循环可能会导致无限环!

另一种简单的方法是进行以下操作:

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

&&表示和 - 或执行以下命令,如果上一个是 true

||是指或 - 或执行,如果上一个是 false

[[ -z $(expansion) ]]表示返回 true 如果扩展输出为 null

这条线基本上就像是双重负面的:"返回 true 如果字符串是在file.file中找不到;然后echo 找不到,如果 true 找到如果 false "

示例:

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

最新更新