Use grep
's -l
option to list the paths of files with matching contents, then print the contents of these files using cat
.
grep -lR 'regex' 'directory' | xargs -d '\n' cat
The command from above cannot handle filenames with newlines in them.
To overcome the filename with newlines issue and also allow more sophisticated checks you can use the find
command.
The following command prints the content of all regular files in directory
.
find 'directory' -type f -exec cat {} +
To print only the content of files whose content matches the regexes regex1
and regex2
, use
find 'directory' -type f \
-exec grep -q 'regex1' {} \; -and \
-exec grep -q 'regex2' {} \; \
-exec cat {} +
The linebreaks are only for better readability. Without the \
you can write everything into one line.
Note the -q
for grep
. That option supresses grep
's output. grep
's exit status will tell find
whether to list a file or not.