if 语句中的 grep 命令

grep command in an if statement

#!/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 接受命令并计算其 returns 值。 grep匹配成功,不匹配失败。所以你可能只想做:

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

注意应该使用双引号,这样"$searchT"被展开,它的值作为参数传递给grep,不需要cat.

#!/bin/bash

if [ $((n=$(grep -wic "$searchT" test.txt))) -ge 0 ]; then
    echo "found ${n}"
else
    echo "not found ${n}"
fi

根据评论修改:

#!/bin/bash

if n=$(grep -wic "$searchT" test.txt); then
    echo "found ${n}"
else
    echo "not found ${n}"
fi

这是缓存结果的另一种方法:mapfile 将其标准输入消耗到一个数组中,每一行都是一个数组元素。

mapfile -t results < <(grep -wi "$searchT" test.txt)
num=${#results[@]}

if ((num == 0)); then
    echo "no match found"
else
    echo "found $num matches"
    printf "%s\n" "${results[@]}"
fi