如何解决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
。
这是另一种缓存结果的方法:mapfile
将其 stdin 消耗到一个数组中,每一行都是一个数组元素。
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
,
#!/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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。