如何测试如果文件存在与Bash shell中的字符串? [英] How to test if string exists in file with Bash shell?

查看:174
本文介绍了如何测试如果文件存在与Bash shell中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含目录名的文件:

my_list.txt

  / tmp目录
/ var / tmp目录

我想在Bash中,检查之前,如果该名称的文件已经存在,我会添加一个目录名。


解决方案

 的grep -Fxq$ FILENAMEmy_list.txt

退出状态是0(真)如果该名称被发现,1(假)如果没有,那么:

 如果grep的-Fxq$ FILENAMEmy_list.txt
然后
    #code。如果发现
其他
    #code。如果没有找到
科幻

下面是的手册页的grep

 的grep [选项]模式[FILE ...]-F,--fixed串
       国米preT模式作为固定字符串列表,由新 - 分离
       线,其中任何一个是被匹配。-x,--line,正则表达式
       只选择那些整条生产线完全匹配匹配。-q,--quiet,--silent
       安静;不写任何东西到标准输出。退出被立即
       ately零状态,如果找到任何匹配,即使错误
       被检测到。另请参见-s或--no的消息选项。

I have a file that contains directory names:

my_list.txt :

/tmp
/var/tmp

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

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆