string - 如何使用 Bash 测试文件中是否存在字符串?

标签 string bash file

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

my_list.txt:

/tmp
/var/tmp

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

最佳答案

grep -Fxq "$FILENAME" my_list.txt

如果找到该名称,则退出状态为 0(真),否则为 1(假),因此:

if grep -Fxq "$FILENAME" my_list.txt
then
    # code if found
else
    # code if not found
fi

说明

这里是the man page for grep的相关部分:

grep [options] PATTERN [FILE...]

-F, --fixed-strings

        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

        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 选项,并根据退出状态检测错误:

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 as grep, cmp, and diff, 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 可能打印的任何错误消息最终都会如您所愿地出现在控制台上。

为了处理这三种情况,我们可以使用case语句:

case `grep -Fx "$FILENAME" "$LIST" >/dev/null; echo $?` in
  0)
    # code if found
    ;;
  1)
    # code if not found
    ;;
  *)
    # code if an error occurred
    ;;
esac

关于string - 如何使用 Bash 测试文件中是否存在字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4749330/

相关文章:

bash - 检查是否在 bash 中设置了第 n 位

linux - Bash - while 循环语法错误

bash - 如何在目录中搜索文件,然后使用 ffmpeg 将该目录的名称刻录到里面的文件中?

javascript - 读取文件行时控制加载顺序

python - For 循环中的整个字符串,而不仅仅是逐个字符

c# - 是否可以在编译时/运行时在 C# 中生成所有标记字符串的列表?

c - 程序写入socket后自动关闭

PHP ftp_put 警告 警告 : ftp_put() [function. ftp-put] : Type set to I. in

java - 如何将字符串转换为二维数组 (java)(GameBoard)

r - 优化 R 中的正则表达式以进行子字符串提取