【问题标题】:grep command in an if statementif 语句中的 grep 命令
【发布时间】:2021-06-21 03:35:44
【问题描述】:
#!/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 命令比较的值。

【问题讨论】:

  • 变量$searchT 不会在单引号内展开。改用双引号:"$searchT"

标签: bash unix scripting


【解决方案1】:

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

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

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

【讨论】:

  • 它仍然无法匹配
  • 我什至尝试在 if 语句中使用 $(cat test.txt | grep '$searchT' && wc -l),这样如果输出为 -ge 大于 1,则回显命令。
  • 你需要使用双引号。您正在搜索文字字符串 $searchT 而不是输入的字符串。
  • 另外,grep "$searchT" && wc -l 不会将grep 的输出发送到 wc。相反,如果有任何匹配,wc -l 将从其标准输入中读取,这(如果您以交互方式运行)意味着它将阻止等待您在 tty 中输入内容。
【解决方案2】:

这是另一种缓存结果的方法: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

【讨论】:

    【解决方案3】:
    #!/bin/bash
    
    if [ $((n=$(grep -wic "$searchT" test.txt))) -ge 0 ]; then
        echo "found ${n}"
    else
        echo "not found ${n}"
    fi
    

    基于cmets修改:

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

    【讨论】:

    • 这行得通,但它是一个糟糕的反模式。这不是正确的做法。
    • @WilliamPursell,需要详细说明吗?
    • 只是if n=$(grep -wic "$searchT" test.txt); then 为什么[ge 比较。
    • 确认! if n=$( grep ..) 更糟糕!这不会检查n 是否为零,它会检查grep 的状态,所以你不妨只做if grep ... 并停止混淆读者!
    • 如果你想保留一些来自grep的数据,那么if n=$(grep...是合理的。
    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多