
也許這有點奇怪 - 也許還有其他工具可以做到這一點,但是,嗯......
我使用以下經典的 bash 命令來查找包含某個字串的所有檔案:
find . -type f | xargs grep "something"
我有大量不同深度的文件。第一次出現“某事”對我來說已經足夠了,但是 find 繼續搜索,並且需要很長時間才能完成其余文件。我想做的是從 grep 返回 find 的“反饋”,以便 find 可以停止搜尋更多檔案。這樣的事可能嗎?
答案1
只需將其保留在 find 範圍內即可:
find . -type f -exec grep "something" {} \; -quit
它是這樣運作的:
-exec
當-type f
意志成真時,意志就會發揮作用。並且因為當匹配時grep
傳回0
(success/true) ,因此將被觸發。-exec grep "something"
-quit
答案2
find -type f | xargs grep e | head -1
正是這樣做的:當head
終止時,管道的中間元素會收到“損壞的管道”信號通知,依次終止,並通知find
.您應該會看到一則通知,例如
xargs: grep: terminated by signal 13
這證實了這一點。
答案3
要在不更改工具的情況下執行此操作:(我喜歡 xargs)
#!/bin/bash
find . -type f |
# xargs -n20 -P20: use 10 parallel processes to grep files in batches of 20
# grep -m1: show just on match per file
# grep --line-buffered: multiple matches from independent grep processes
# will not be interleaved
xargs -P10 -n20 grep -m1 --line-buffered "$1" 2> >(
# Error output (stderr) is redirected to this command.
# We ignore this particular error, and send any others back to stderr.
grep -v '^xargs: .*: terminated by signal 13$' >&2
) |
# Little known fact: all `head` does is send signal 13 after n lines.
head -n 1