[英]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
I need to find both string1 and string 2 in same line from file1.txt, is there any better way to write this or this is the good already? 我需要在file1.txt的同一行找到string1和string 2,有没有更好的方法来写这个或者这已经好了? thanks for all the help, I am new to shell programming.
感谢所有的帮助,我是shell编程的新手。
you can use 您可以使用
grep -e "string1.*string2" file1.txt
so long as you're expecting string2 to come second and there is no overlap 只要你期望string2成为第二名并且没有重叠
Alternatively the grep piped into grep is the standard approach. 或者,用grep管道输入grep是标准方法。 Maybe using a variable
也许使用变量
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
Usually, you only need to use $?
通常,你只需要使用
$?
if you need to compare it against several different values. 如果你需要将它与几个不同的值进行比较。 In this case, you only care about 0-vs-non-zero, so just run the
grep
commands in the if
statement itself. 在这种情况下,您只关心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.