if语句中的grep命令

#!/bin/bash
read -p "enter search term here: " searchT

if [[ $(cat test.txt | grep -wi '$searchT') ]]; then     
    echo "$(cat test.txt | grep '$searchT' && wc -l) number of matches found"
    echo $(cat test.txt | grep '$searchT')

else echo "no match found"    

fi

exit 0

如果if statement为真,我如何使脚本运行。当我运行脚本时,脚本将输出else语句。因为没有值可以与 grep 命令进行比较。

回答

不清楚您要匹配的内容,但请记住,它if接受一个命令并评估其返回值。 grep 如果匹配则成功,如果不匹配则失败。所以你可能只想做:

if grep -q -wi "$searchT" test.txt; then
   ...
fi 

请注意,您应该使用双引号,以便扩展 "$searchT" 并将其值作为参数传递给 grep,并且不需要cat.


以上是if语句中的grep命令的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>