[英]bash shell: grepping two strings in same line and use it in if-condition
grep string1 file1.txt | grep -q string2
if [ $? == 0 ]; then
echo "both string1 and 2 found"
else
echo "either or both missing"
fi
我需要在file1.txt的同一行找到string1和string 2,有没有更好的方法来写这个或者这已经好了? 感谢所有的帮助,我是shell编程的新手。
您可以使用
grep -e "string1.*string2" file1.txt
只要你期望string2成为第二名并且没有重叠
或者,用grep管道输入grep是标准方法。 也许使用变量
result=`grep string1 file1.txt | grep string2`
if [ `echo "$result"|wc -w` == 0 ];then
echo "a"
else
echo "b"
fi
如果订单无关紧要,它已经相当不错了,但您可以将其缩短为:
grep string1 file1.txt | grep -q string2 && echo found || echo not found
通常,你只需要使用$?
如果你需要将它与几个不同的值进行比较。 在这种情况下,您只关心0-vs-non-zero,因此只需在if
语句本身中运行grep
命令。
if grep string1 file1.txt | grep -q string2; then
echo "both string1 and 2 found"
else
echo "either or both missing"
fi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.