2017-03-26 100 views
0

我有幾行(我不知道有多少)。我通過管道將它們發送到grep。我需要找出是否所有的行都是由grep選擇的。然後我需要寫好(如果他們都被選中)或不好。我該怎麼做?Bash:grep對所有行返回true

+0

你的問題不清楚。你在哪裏搜索你正在翻閱的線路?從另一個文件? – codeforester

+1

我猜測你在尋求什麼 - 如果我誤解了你的問題,請解釋一下。 –

回答

5

一種方法是使用-v--invert-match)標誌,它告訴grep來搜索匹配您的圖案線條。

,如果它發現它有任何輸出線可以結合起來,與該-q--quiet--silent)標誌,它告訴grep到實際上沒有產生任何輸出,並剛剛成功退出。

然後,如果任何行與您的模式不匹配,則可以檢查退出狀態:zero(「success」/「true」),否則返回非零(「failure」/「false」)。所以:

if ... | grep -qv ... ; then 
    echo Not OK 
else 
    echo OK 
end 
0

如果你有兩個文件file1file2,你可以檢查的file1所有線路都在file2本:

if ! grep -qvxFf file2 file1; then 
    echo "All lines of file1 are present in file2' 
else 
    echo "Some lines of file1 are not present in file2' 
fi 

如果file1來自一個命令執行,然後使用進程替代:

if ! grep -qvxFf file2 <(file1-command); then 
    echo "All lines are present in file2' 
else 
    echo "Some lines are not present in file2' 
fi 
  • x整行匹配
  • F治療的行作爲字符串,而不是圖案

file1匹配的至少一條線在file2所有行,grep -qvxFf file2 file1給出的退出代碼爲1,這表明匹配返回任何輸出,-v(逆匹配)有效。

0

如果我理解正確的話,你目前有:

some-process-generating-lines | 
grep -e 'some selection criterion' 

並且要檢查傳入grep行數是否相同的行數從它出來 - 是否每個輸入行都滿足選擇標準。

您需要能夠統計和輸出兩行。計數線很容易 - 通過wc -l傳遞輸出並捕獲整個結果。

lines_out=$(some-process-generating-lines | 
      grep -e 'some selection criterion' | 
      wc -l) 

計算行數並不困難。最簡單的方法是讓tee命令創建輸入數據的副本grep,然後數着:

tmpfile=$(mktemp ${TMPDIR:-/tmp}/soq.XXXXXXXX) 
trap "rm -f $tmpfile; exit 1" 0 1 2 3 13 15 

lines_out=$(some-process-generating-lines | 
      tee $tmpfile | 
      grep -e 'some selection criterion' | 
      wc -l) 
lines_in=$(wc -l <$tmpfile) 

rm -f $tmpfile 
trap 0 1 2 3 13 15 

if [ "$lines_in" = "$lines_out" ] 
then echo OK 
else echo Not OK 
fi 

trap東西保證(或試圖保證)的臨時文件,即使清理過程中斷(或發送退出,掛斷,管道或終止信號)。 mktemp命令生成一個唯一的文件名。其他的相當直接,我相信。

0

假設您的問題是由這個定義:

some-process-generating-lines | 
    grep -E 'some selection criterion' 

而且要算在線路進出,你可以做這樣的事情:
printf "aaa\nbbb\nccc\n"只是代碼生成輸出的一個例子。

#!/bin/bash 

f() { cat "$1" | tee "$x" | grep -E "aaa|bbb" >"$y"; } 

x=>(a=$(wc -l); echo "Lines in : $a") \ 
    y=>(b=$(wc -l); echo "Lines out: $b") \ 
     f <(printf "aaa\nbbb\nccc\n") 

或者沒有貓的選項(不容易跟隨,但技術上更加正確的):

f() { <"$1" tee "$x" | grep -E "aaa|bbb" >"$y"; } 

在執行時的輸出將是:

$ ./script.sh 
Lines out: 2 
Lines in : 3 

沒有文件使用後清洗。

+0

你絕對想要在那裏避免[無用的'cat'](http://www.iki.fi/era/unix/award.html)。 – tripleee

+0

@tripleee完成(好吧,其中一半,因爲我覺得更不容易遵循)。 – sorontar