Jos*_*hua 4 bash grep if-statement while-loop
我正在尝试报告使用 grep 和 while 找到的行。
我知道您可以使用以下内容来比较来自 input.txt 的字符串列表,并在您的目标文件中找到它们,如下所示:
grep -f inputs.txt file_to_check
Run Code Online (Sandbox Code Playgroud)
我想要的是读取输入字符串的每一行并在循环中单独grep它们。
所以我尝试了以下方法:
cat inputs.txt | while read line; do if grep "$line" filename_to_check; then echo "found"; else echo "not found"; fi; done
Run Code Online (Sandbox Code Playgroud)
当我将输出重定向到文件时,这不会返回任何内容。
while read line
do
if grep "$line" file_to_check
then echo "found"
else
echo "not found"
fi
done < inputs.txt
Run Code Online (Sandbox Code Playgroud)
与第一个相同,但从我发现的更好。
我知道它会逐行迭代,因为我可以用 echo $line 替换 grep 并打印每一行;但任一方法都不会返回类似 grep -f 的内容,而是显示:
not found
not found
not found
.
. etc.
Run Code Online (Sandbox Code Playgroud)
所以我正在寻找的是它会遍历每一行并使用 if 语句通过 grep 检查它以确定 grep 是否真的找到它的东西。我知道我可能没有所有正确的逻辑,但我想要的输出应该是这样的:
Found *matching line in file_to_check*
Found *matching line in file_to_check*
Not Found $line *(string that does not match)*
.
. etc.
Run Code Online (Sandbox Code Playgroud)
您还可以使用&&和||运算符:
while read line; do
grep -q "$line" file_to_check && echo "$line found in file_to_check" || echo "$line not found in file_to_check"
done < inputfile > result.txt
Run Code Online (Sandbox Code Playgroud)
-qgrep的参数只是输出一个状态码:
$line找到,它将输出0(真)之后的命令&&将被评估1(False)||后将评估的命令好吧,你的 if 语句是相当自由的形式,你可能需要稍微清理一下它以便 bash 能够读取它。例如:
if [ "$(grep "$line" file_to_check)" != "" ]; then
echo "found: $line"
else
echo "not found: $line"
fi
Run Code Online (Sandbox Code Playgroud)
如果 grep 命令找到该行,则该 if 语句将评估 true,因为如果找到该行,它将吐出该行并且不等于“”或空字符串。