Edit: I misinterpreted the question in my original answer.... I have edited it to produce the desired result...
I was only showing the file name in the output. I edited this answer to use that output to show the entire file by using less (as Ravexina's answer suggests)
...in addition, this will only return the files (in less
) that have been matched by grep when searching through a directory(s).
....and I added -I
to ignore binary files, they may make the less
interaction messy. Remove it if you need to search binary files or files that grep may "think" are binary.
Use the "with-filename" flag with grep to show the file. (the flag is -H
)
I am assuming you are combing through a directory and each of the files in them. If searching outside of current directory, use the *
to prevent "is a directory" error with no results.
grep -HI pattern /directory/* | less -p pattern $(awk -F ":" '{print $1}')
or
grep --with-filename -I pattern /directory/* | less -p pattern $(awk -F ":" '{print $1}')
or if drilling down into sub-directories...
grep -rHI pattern /directory/* | less -p pattern $(awk -F ":" '{print $1}')
I don't like entering the pattern twice, it could use improvement