Bash脚本 - 检查文件是否包含特定行

use*_*065 14 string bash if-statement conditional-statements

我需要检查文件是否包含特定行.这个文件是由某人连续写的,所以我把检查放在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
Run Code Online (Sandbox Code Playgroud)

该文件包含文本和多行.

fst*_*tab 14

如果$FILE包含文件名并$STRING包含要搜索的字符串,则可以使用以下命令显示文件是否匹配:

if [ ! -z $(grep "$STRING" "$FILE") ]; then echo "FOUND"; fi
Run Code Online (Sandbox Code Playgroud)

  • imho这确实没有回答这个问题,因为如果$ STRING是一行的一部分,它也会报告"FOUND".问题是关于特定**线**的存在.'grep'^ $ STRING"'$'`浮现在脑海中,但在这里不够通用,因为STRING可能包含一些可能被误认为正则表达式的元素.这也适用于所提出的解决方案. (7认同)
  • 你应该引用你的变量:真实数据可能不只是一个单词,文件名可以包含空格.无用的cat:grep接受文件名参数. (4认同)
  • 在我自己的 bash 脚本中使用它时,我不断收到“[:状态:预期的二元运算符”。我将其更改为双方括号并且有效 (2认同)

Ant*_*huk 13

来自 grep 的人:

-q, --quiet, --silent
    Quiet; do not write anything to standard output.  Exit immediately with zero status if any match is found, even if an error was detected.  Also see the -s or --no-messages option.
-F, --fixed-strings
    Interpret PATTERNS as fixed strings, not regular expressions.
-x, --line-regexp
    Select only those matches that exactly match the whole line.  For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $.
Run Code Online (Sandbox Code Playgroud)
-q, --quiet, --silent
    Quiet; do not write anything to standard output.  Exit immediately with zero status if any match is found, even if an error was detected.  Also see the -s or --no-messages option.
-F, --fixed-strings
    Interpret PATTERNS as fixed strings, not regular expressions.
-x, --line-regexp
    Select only those matches that exactly match the whole line.  For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $.
Run Code Online (Sandbox Code Playgroud)

如果您需要检查整行,请使用-x标志:

# Inline
grep -q -F "$STRING" "$FILE" && echo 'Found' || echo 'Not Found'
grep -q -F "$STRING" "$FILE" || echo 'Not Found'

# Multiline
if grep -q -F "$STRING" "$FILE"; then
  echo 'Found'
else
  echo 'Not Found'
fi

if ! grep -q -F "$STRING" "$FILE"; then
  echo 'Not Found'
fi
Run Code Online (Sandbox Code Playgroud)

  • 这次真是万分感谢。我对我的用例进行了快速性能检查,然后将其与“awk”答案进行了比较。原始运行时间:0.4s;使用`awk`:0.3秒;使用这个答案:0.09s。 (2认同)

Col*_*ney 6

轮询文件的修改时间,并在字符串发生变化时grep:

while :; do
    a=$(stat -c%Y "$FILE") # GNU stat
    [ "$b" != "$a" ] && b="$a" && \
        grep -q "$STRING" "$FILE" && echo FOUND
    sleep 1
done
Run Code Online (Sandbox Code Playgroud)

注意:BSD用户应该使用 stat -f%m