Use*_*r10 0 unix bash scripting
#!/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
Run Code Online (Sandbox Code Playgroud)
如果if statement为真,我如何使脚本运行。当我运行脚本时,脚本将输出else语句。因为没有值可以与 grep 命令进行比较。
不清楚您要匹配的内容,但请记住,它if接受一个命令并评估其返回值。 grep 如果匹配则成功,如果不匹配则失败。所以你可能只想做:
if grep -q -wi "$searchT" test.txt; then
...
fi
Run Code Online (Sandbox Code Playgroud)
请注意,您应该使用双引号,以便扩展 "$searchT" 并将其值作为参数传递给 grep,并且不需要cat.
这是缓存结果的另一种方法: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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
761 次 |
| 最近记录: |