簡體   English   中英

bash shell:在同一行中grepping兩個字符串並在if-condition中使用它

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM