string Bash 脚本 - 检查文件是否包含特定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22861580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script - Check if a file contains a specific line
提问by user3472065
I need to check if a file contains a specific line. This file is written continuosly by someone, so i put the check inside a while loop.
我需要检查文件是否包含特定行。这个文件是由某人连续编写的,所以我把支票放在一个 while 循环中。
FILE="/Users/test/my.out"
STRING="MYNAME"
EXIT=1
while [ $EXIT -ne 0 ]; do
if [ -f $FILE ] ; then CHECK IF THE "STRING" IS IN THE FILE - IF YES echo "FOUND"; EXIT=0; fi
done
The file contains text and multiple lines.
该文件包含文本和多行。
采纳答案by fstab
if $FILE
contains the file name and $STRING
contains the string to be searched,
then you can display if the file matches using the following command:
如果$FILE
包含文件名并$STRING
包含要搜索的字符串,则可以使用以下命令显示文件是否匹配:
if [ ! -z $(grep "$STRING" "$FILE") ]; then echo "FOUND"; fi
回答by Cole Tierney
Poll the file's modification time and grep for the string when it changes:
轮询文件的修改时间和 grep 更改时的字符串:
while :; do
a=$(stat -c%Y "$FILE") # GNU stat
[ "$b" != "$a" ] && b="$a" && \
grep -q "$STRING" "$FILE" && echo FOUND
sleep 1
done
Note: BSD users should use stat -f%m
注意:BSD 用户应该使用 stat -f%m
回答by Josh Jolly
Try:
尝试:
while : ;do
[[ -f "$FILE" ]] && grep -q "$STRING" "$FILE" && echo "FOUND" && break
done
This will loop continuously without waiting, you may want to add a waiting period (eg 5 seconds in this example):
这将连续循环而无需等待,您可能需要添加一个等待时间(例如,在此示例中为 5 秒):
while : ;do
[[ -f "$FILE" ]] && grep -q "$STRING" "$FILE" && echo "FOUND" && break
sleep 5
done
回答by Holger Brandl
A more rigorous check to test if a given line$STRING is contained in a file FILE would be
更严格的检查来测试给定的行$STRING 是否包含在文件 FILE 中
awk '##代码## == "'${STRING}'"' $FILE
This in particular addresses my concerns with @fstab's answer (which also applies to all other previous answers): It checks the complete line and not just for substring presence within a line (as done with the grep solutions from above).
这特别解决了我对@fstab 答案的担忧(这也适用于所有其他以前的答案):它检查完整的行,而不仅仅是一行中是否存在子字符串(如上面的 grep 解决方案所做的那样)。
The loop could be done as shown in the other answers.
可以按照其他答案中所示完成循环。