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)
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)
轮询文件的修改时间,并在字符串发生变化时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