grep -rlZI "bananas" . | xargs -0 cat > out.txt
The -lZ
outputs a null-separated list of the names of matching files:
-l, --files-with-matches
Suppress normal output; instead print the name of each input
file from which output would normally have been printed. The
scanning will stop on the first match.
-Z, --null
Output a zero byte (the ASCII NUL character) instead of the
character that normally follows a file name. For example, grep
-lZ outputs a zero byte after each file name instead of the
usual newline. This option makes the output unambiguous, even
in the presence of file names containing unusual characters like
newlines. This option can be used with commands like find
-print0, perl -0, sort -z, and xargs -0 to process arbitrary
file names, even those that contain newline characters.
If your version of grep doen't provide the -Z
option, then you can fall back to plain -l
which will still handle filenames containing whitespace (excluding newlines obviously) provided you set the xargs
delimiter to newline as well:
grep -rlI "bananas" . | xargs -d '\n' cat > out.txt
grep -rnI "bananas" | cut -d: -f1 | xargs cat >> result.txt
. Do you need explanation?