
어쩌면 조금 이상할 수도 있습니다. 그리고 이 작업을 수행하는 다른 도구가 있을 수도 있지만 글쎄요..
다음과 같은 클래식 bash 명령을 사용하여 일부 문자열이 포함된 모든 파일을 찾습니다.
find . -type f | xargs grep "something"
여러 깊이에 걸쳐 많은 수의 파일이 있습니다. "무언가"가 처음 나타나는 것만으로도 충분하지만 find는 검색을 계속하고 나머지 파일을 완료하는 데 오랜 시간이 걸립니다. 내가 하고 싶은 것은 find가 더 많은 파일 검색을 중단할 수 있도록 grep에서 find로의 "피드백"과 같은 것입니다. 그런 일이 가능합니까?
답변1
간단히 find 영역 내에 보관하세요.
find . -type f -exec grep "something" {} \; -quit
작동 방식은 다음과 같습니다.
의지 는 참일 -exec
때 작동합니다 . -type f
그리고 일치하는 항목이 있을 때 (성공/true)를 grep
반환 하므로 이 트리거됩니다.0
-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