Answers:
如果只需要匹配的文件:
find . -type f -exec bash -c 'grep -q "matching string here" < <(head -n 50 "$1")' _ {} \; -printf '%p\n'
要么
find . -type f -exec bash -c 'grep -q "matching string here" < <(head -n 50 "$1") && printf '%s\n' "$1"' _ {} \;
如果只需要匹配的字符串:
find . -type f -exec head -n 50 {} \; | grep "matching string here"
或更好,
find . -type f -exec head -q -n 50 {} + | grep "matching string here"
如果您同时想要:
find . -type f -exec bash -c 'mapfile -t a < <(head -n 50 "$1" | grep "matching string here"); printf "$1: %s\n" "${a[@]}"' _ {} \;
备注。
sed
代替组合head
- 可能会稍微容易一些grep
。-exec ... +
in each method, but then you'll have to code your inner loop yourself! (trivial exercise left to the reader). This might be very slightly more efficient if you have a gazillion files.If you need the grep output as in the original, you could do:
find . -type f | while read f; do
if head -n 50 "$f"|grep -s "matching string here"; then
grep "matching string here" "$f" /dev/null
fi
done
If you only need the file names you can replace the 2nd grep with echo "$f"
.
You'll need to combine a few different utilities to get the desired functionality. Use the find
command to recurse the directories, find all files and execute the head
command on each file found. The head
command can be used to dump only the first 50 lines of each file. Finally, pipe the output to grep to search for your desired string.
find . -type f -exec head -n 50 {} ";" | grep "matching string here"