Linux bashshell:将同一行中的两个字符串变灰,并在if条件下使用它
我需要在file1.txt的同一行中找到string1和string2,有没有更好的方法来写这个或者这个已经很好了?谢谢您的帮助,我对shell编程还不熟悉。您可以使用Linux bashshell:将同一行中的两个字符串变灰,并在if条件下使用它,linux,bash,shell,Linux,Bash,Shell,我需要在file1.txt的同一行中找到string1和string2,有没有更好的方法来写这个或者这个已经很好了?谢谢您的帮助,我对shell编程还不熟悉。您可以使用 grep string1 file1.txt | grep -q string2 if [ $? == 0 ]; then echo "both string1 and 2 found" else echo "either or both missing" fi 只要您希望string2排在第二位,并且没有重叠
grep string1 file1.txt | grep -q string2
if [ $? == 0 ]; then
echo "both string1 and 2 found"
else
echo "either or both missing"
fi
只要您希望string2排在第二位,并且没有重叠
或者,将grep管道引入grep是标准方法。也许使用一个变量
grep -e "string1.*string2" file1.txt
你可以用
grep string1 file1.txt | grep -q string2
if [ $? == 0 ]; then
echo "both string1 and 2 found"
else
echo "either or both missing"
fi
只要您希望string2排在第二位,并且没有重叠
或者,将grep管道引入grep是标准方法。也许使用一个变量
grep -e "string1.*string2" file1.txt
如果订单不重要,它已经相当不错了,但您可以将其缩短为:
grep string1 file1.txt | grep-q string2&&echo found | | echo not found
如果顺序不重要,它已经很好了,但您可以将其缩短为:
grep string1 file1.txt | grep-q string2&&echo found | | echo not found
通常,如果需要将其与几个不同的值进行比较,只需使用$?
。在本例中,您只关心0与非零,因此只需运行if
语句本身中的grep
命令即可
result=`grep string1 file1.txt | grep string2`
if [ `echo "$result"|wc -w` == 0 ];then
echo "a"
else
echo "b"
fi
通常,如果需要将其与几个不同的值进行比较,则只需使用
$?
。在本例中,您只关心0与非零,因此只需运行if
语句本身中的grep
命令即可
result=`grep string1 file1.txt | grep string2`
if [ `echo "$result"|wc -w` == 0 ];then
echo "a"
else
echo "b"
fi
当顺序无关紧要时,您可以使用备用顺序
grep-e“string1.*string2 | string2.*string1”file1.txt,或使用备用顺序grep-e“string1.*string2 | string2.*string1”file1.txt