如何从bash脚本中搜索文件中的表达式?

时间:2010-03-13 18:24:09

标签: bash

我有一个bash脚本。 我需要查看文件中是否存在“text”,如果存在则执行某些操作。

6 个答案:

答案 0 :(得分:4)

如果您需要对包含该文本的所有文件执行命令,则可以将grepxargs合并。例如,这将删除包含“yourtext”的所有文件:

grep -l "yourtext" * | xargs rm

要搜索单个文件,请使用if grep ...

if grep -q "yourtext" yourfile ; then
  # Found
fi

答案 1 :(得分:2)

以下内容可以满足您的需求。

grep -w "text" file > /dev/null

if [ $? -eq 0 ]; then
   #Do something
else
   #Do something else
fi

答案 2 :(得分:1)

grep是你的朋友

答案 3 :(得分:1)

您可以将grep放在if语句中,然后使用-q标记使其静音。

if grep -q "text" file; then
    :
else
    :
fi

答案 4 :(得分:0)

cat <file> | grep <"text">并使用test $?

检查返回代码

查看优秀: Advanced Bash-Scripting Guide

答案 5 :(得分:0)

只需使用shell

while read -r line
do
  case "$line" in
   *text* ) 
        echo "do something here"
        ;;
   * )  echo "text not found"
  esac
done <"file"