如何使用Bash测试文件中是否存在字符串? [英] How to test if string exists in file with Bash?
问题描述
我有一个包含目录名称的文件:
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
的手册页的相关部分:>
grep [options] PATTERN [FILE...]
-F
,--fixed-strings
将PATTERN解释为固定字符串列表,用换行符分隔,其中任何一个都将被匹配.
Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.
-x
,--line-regexp
仅选择与整行完全匹配的匹配项.
Select only those matches that exactly match the whole line.
-q
,--quiet
,--silent
安静;不要在标准输出中写任何东西.如果发现任何匹配项,则立即以零状态退出,即使检测到错误也是如此.另请参见-s
或--no-messages
选项.
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.
错误处理
正如注释中正确指出的那样,以上方法默默地将错误情况视为已找到字符串.如果要以其他方式处理错误,则必须省略-q
选项,并根据退出状态检测错误:
Error handling
As rightfully pointed out in the comments, the above approach silently treats error cases as if the string was found. If you want to handle errors in a different way, you'll have to omit the -q
option, and detect errors based on the exit status:
通常,如果找到选定的行,则退出状态为0,否则为1.但是,如果发生错误,则退出状态为2,除非使用
-q
或--quiet
或--silent
选项并且找到选定的行.但是请注意,对于grep
,cmp
和diff
之类的程序,POSIX仅要求在出现错误的情况下退出状态大于1.因此,出于可移植性考虑,建议使用针对此一般条件进行测试的逻辑,而不是与2严格相等.
Normally, the exit status is 0 if selected lines are found and 1 otherwise. But the exit status is 2 if an error occurred, unless the
-q
or--quiet
or--silent
option is used and a selected line is found. Note, however, that POSIX only mandates, for programs such asgrep
,cmp
, anddiff
, that the exit status in case of error be greater than 1; it is therefore advisable, for the sake of portability, to use logic that tests for this general condition instead of strict equality with 2.
要禁止来自grep
的正常输出,可以将其重定向到/dev/null
.请注意,标准错误仍然是无向的,因此grep
可能会打印的任何错误消息都将最终出现在控制台上.
To suppress the normal output from grep
, you can redirect it to /dev/null
. Note that standard error remains undirected, so any error messages that grep
might print will end up on the console as you'd probably want.
要处理这三种情况,我们可以使用case
语句:
To handle the three cases, we can use a case
statement:
case `grep -Fx "$FILENAME" "$LIST" >/dev/null; echo $?` in
0)
# code if found
;;
1)
# code if not found
;;
*)
# code if an error occurred
;;
esac
这篇关于如何使用Bash测试文件中是否存在字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!