检查变量是否与 BASH 中文件中某处的行匹配的最简单方法是什么



我需要检查是否可以在文件中的某个地方找到变量(从头到尾匹配确切的行),例如:

if [ "$find" is in file.txt ]
then
    echo "Found."
else
    echo "Not found."
fi

我一直在使用grep -c '^$find$' > count.txt,然后count="$(cat count.txt)",然后检查$count是否大于"0",但这种方法似乎效率低下。

检查变量是否完全作为文件中某处的一行找到的最简单方法是什么?

使用 grep

grep -q "$find" file.txt && echo "Found." || echo "Not found."

如果要匹配整行,请使用-x选项:

grep -xq "$find" file.txt && echo "Found." || echo "Not found."

引用man grep

  -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.
  -x, --line-regexp
          Select only those matches that exactly match the whole line.

以上也可以写成:

if grep -xq "$find" file.txt; then
    echo "Found."
else
    echo "Not found."
fi

相关内容

  • 没有找到相关文章

最新更新