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

如何从bash脚本中搜索文件中的表达式?,bash,Bash,我有一个bash脚本。 我需要查看文件中是否存在“文本”,如果它存在,我需要执行一些操作。这里是您的朋友吗这里是您的朋友吗下面类似的操作可以满足您的需要 grep -w "text" file > /dev/null if [ $? -eq 0 ]; then #Do something else #Do something else fi 下面的内容可以满足您的需要 grep -w "text" file > /dev/null if [ $? -eq 0 ];

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

这里是您的朋友吗这里是您的朋友吗下面类似的操作可以满足您的需要

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

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

下面的内容可以满足您的需要

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

if [ $? -eq 0 ]; then
   #Do something
else
   #Do something else
fi
cat|grep
并使用
test$?

查看优秀的:

cat|grep
并使用
test$?

查看优秀的:

如果需要对包含文本的所有文件执行命令,可以将
grep
xargs
组合使用。例如,这将删除包含“yourtext”的所有文件:

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

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

如果需要对包含文本的所有文件执行命令,可以将
grep
xargs
组合使用。例如,这将删除包含“yourtext”的所有文件:

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

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

您可以将
grep
放在
if
语句中,并且可以使用
-q
标志使其静音

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

您可以将
grep
放在
if
语句中,并且可以使用
-q
标志使其静音

if grep -q "text" file; then
    :
else
    :
fi
就用这个外壳吧

while read -r line
do
  case "$line" in
   *text* ) 
        echo "do something here"
        ;;
   * )  echo "text not found"
  esac
done <"file"
读取时-r行
做
大写“$line”
*文本*)
echo“在这里做点什么”
;;
*)回显“未找到文本”
以撒
完成只需使用外壳

while read -r line
do
  case "$line" in
   *text* ) 
        echo "do something here"
        ;;
   * )  echo "text not found"
  esac
done <"file"
读取时-r行
做
大写“$line”
*文本*)
echo“在这里做点什么”
;;
*)回显“未找到文本”
以撒
完成我更喜欢
if[$(grep-c“text”文件)-gt 0]
,但这是一样的。马丁的方法(使用
grep-q
)比这两种方法都更快(不搜索整个文件,只搜索第一个匹配项)和更干净(IMHO)。我更喜欢
if[$(grep-c“text”文件)-gt 0]
但这是一样的。Martin的方法(使用
grep-q
)比这两种方法都更快(不搜索整个文件,只搜索第一个匹配项),而且更干净。