虽然文件不包含字符串BASH

时间:2017-02-21 20:52:50

标签: bash while-loop

我正在为我的学校制作一个脚本,我想知道如何检查文件,如果文件中没有字符串,请执行代码,但如果是,请继续,如下所示:

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

3 个答案:

答案 0 :(得分: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"

但要注意不要进入无限循环。必须更改字符串或文件,否则循环没有意义。

以上if / while基于命令的返回状态而不是结果。 如果grep在文件中找到字符串将返回0 = success = true 如果grep没有找到字符串将返回1 = not success = false

使用!我们将“false”恢复为“true”以保持循环运行,因为while循环时它会立即循环。

更传统的while循环类似于你的代码但没有无用的cat和额外的管道:

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

答案 1 :(得分:2)

一个简单的if语句,用于测试'{1}}中是否存在'string':

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)确保输出不会写入标准输出。

要测试的简单while循环是'{1}}中不存在'string':

--silent

注意:请注意while循环可能导致无限循环的可能性!

答案 2 :(得分:0)

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

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

&&表示AND - 或执行以下命令,前提是 true

||表示OR - 或者如果前一个是 false

则执行

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

,则返回 true

这一行很像双重否定,基本上: “如果字符串在file.file中未找到,则返回 true ;如果 true ,则返回未找到 ,或者发现如果错误

示例:

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