1

How can I modify grep so that it prints the full file if its entry matches the grep pattern, instead of printing just the matching line?

I tried using grep -C2 to print two lines above and two below but this doesn't always work as the number of lines is not fixed.

I am not just searching a single file, I am searching an entire directory where some files may contain the given pattern and I want those files to be completely printed.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Aniket Gupta
  • 62
  • 1
  • 6

2 Answers2

3

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.

Socowi
  • 25,550
  • 3
  • 32
  • 54
  • Can you modify this so that I can use another grep on whole file of first matches and then printing those whole files which matches both the greps – Aniket Gupta Mar 20 '18 at 17:34
  • @AniketGupta Not so easily, but there is an alternative (see edited answer). – Socowi Mar 20 '18 at 21:41
  • This should make it work with file names containing newlines: `grep --null -lR 'regex' 'directory' | xargs --null cat` – Matthias Braun Jun 09 '23 at 08:06
2

Simple grep + cat combination:

grep 'pattern' file && cat file
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105