Grep to Print all file content
This question already has an answer here:
简单的grep
+ cat
组合:
grep 'pattern' file && cat file
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 -print0 | xargs -0 cat
To print only the content of files whose content match the regexes regex1
and regex2
, use
find 'directory' -type f
-exec grep -q 'regex1' {} ; -and
-exec grep -q 'regex2' {} ; -print0 |
xargs -0 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.
上一篇: 快速unix命令显示文件中间的特定行?
下一篇: Grep打印所有文件内容