如何使用Bash shell测试文件中是否存在字符串? [英] How to test if string exists in file with Bash shell?
本文介绍了如何使用Bash shell测试文件中是否存在字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含目录名称的文件:
I have a file that contains directory names:
my_list.txt
:
/tmp
/var/tmp
如果文件中已经存在该名称,我想在Bash中检查一下目录名。
I'd like to check in Bash before I'll add a directory name if that name already exists in the file.
推荐答案
grep -Fxq "$FILENAME" my_list.txt
如果找到名称,退出状态为0(true),否则为1(false),所以:
The exit status is 0 (true) if the name was found, 1 (false) if not, so:
if grep -Fxq "$FILENAME" my_list.txt
then
# code if found
else
# code if not found
fi
以下是 grep
的手册页:
Here are the relevant sections of the man page for grep
:
grep [options] PATTERN [FILE...]
-F, --fixed-strings
Interpret PATTERN as a list of fixed strings, separated by new-
lines, any of which is to be matched.
-x, --line-regexp
Select only those matches that exactly match the whole line.
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immedi-
ately with zero status if any match is found, even if an error
was detected. Also see the -s or --no-messages option.
这篇关于如何使用Bash shell测试文件中是否存在字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文