Home » Linux » How to show grep result with complete path or file name

How to show grep result with complete path or file name

Posted by: admin November 30, 2017 Leave a comment

Questions:

I need to know the complete file path when I grep.

I use commands like

cat *.log | grep somethingtosearch

Now what I need to show the result with complete file path from where the matched result were taken out.

Help anyone?

Answers:

Assuming you have two log-files in:

  • C:/temp/my.log
  • C:/temp/alsoMy.log

cd to C: and use:

grep -r somethingtosearch temp/*.log

It will give you a list like:

temp/my.log:somethingtosearch
temp/alsoMy.log:somethingtosearch1
temp/alsoMy.log:somethingtosearch2

Questions:
Answers:

Have you tried using the -l flag?

grep -l somethingtosearch

This will return just the paths and file names where the search was found, not the whole lines where the match was made.

Use with -r flag for recursion.

Questions:
Answers:

If you want to see the full paths, I would recommend to cd to the top directory (of your drive if using windows)

cd C:\
grep -r somethingtosearch C:\Users\Ozzesh\temp

Or on Linux:

cd /
grep -r somethingtosearch ~/temp

if you really resist on your file name filtering (*.log) AND you want recursive (files are not all in the same directory), combining find and grep is the most flexible way:

cd /
find ~/temp -iname '*.log' -type f -exec grep somethingtosearch '{}' \;

Questions:
Answers:

for me
grep -b “searchsomething” *.log
worked as I wanted

Questions:
Answers:

The easiest way to print full paths is replace relative start path with absolute path:

grep -r --include="*.sh" "pattern" ${PWD}

Questions:
Answers:

Command:

grep -rl --include="*.js" "searchString" ${PWD}

Returned output:

/root/test/bas.js

Questions:
Answers:

Use:

grep somethingtosearch *.log

and the filenames will be printed out along with the matches.