我有幾行(我不知道有多少)。我通過管道將它們發送到grep
。我需要找出是否所有的行都是由grep
選擇的。然後我需要寫好(如果他們都被選中)或不好。我該怎麼做?Bash:grep對所有行返回true
0
A
回答
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
如果你有兩個文件file1
和file2
,你可以檢查的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
沒有文件使用後清洗。
相關問題
- 1. WPF ListViewItem.IsMouseOver對整行不返回True
- 2. isDirectory()對文件返回true
- 3. 對於所有運行的文件,PHP返回true,如果語句
- 4. 執行的ActionListener返回true
- 5. NSPredicate返回所有對象
- 6. 對於onclick,jQuery回調返回true/false
- 7. dirpagination不返回所有行
- 8. SQL:OPENQUERY不返回所有行
- 9. PHP:Whileloop返回所有行
- 10. 查詢返回所有行
- 11. findDependentRowset返回所有行
- 12. PDO返回所有行
- 13. Laravel find ::返回所有行
- 14. 返回所有行和列
- 15. TcpClient不返回所有行
- 16. 如果所有td.has_pais_dist都有文本,則返回「true」,否則返回「false」
- 17. Netinfo.isConnected.fetch()返回true
- 18. ssh2_auth_none返回true
- 19. setOnLongClickListner返回true
- 20. 返回true
- 21. instance.validate()返回true
- 22. mysql_num_rows返回TRUE
- 23. 爲什麼(true && 1)返回1,但(1 && true)返回true?
- 24. Vim filereadable對用戶腳本返回true,對插件返回false
- 25. 導軌 - 返回了誰的方法返回true的所有記錄
- 26. 具有對象的隊列對於isEmpty()返回true Java
- 27. Ajax - SQL - 返回所有行的行
- 28. mysqli_result類的對象無法轉換爲int並且所有條目返回true
- 29. 鑑於鍵/值對,找到所有滿足並返回true的規則
- 30. MySQL是沒有返回所有的行
你的問題不清楚。你在哪裏搜索你正在翻閱的線路?從另一個文件? – codeforester
我猜測你在尋求什麼 - 如果我誤解了你的問題,請解釋一下。 –