Why does grep sometimes show the file name, sometimes not

grepwildcards

Can somebody please explain to me why I don't get the full path in example 1?

example 1 – returning found line

grep MODIFY /opt/releases/packages/cr_c_cr6/sas/dbms/*/*;
outcome: MODIFY

example 2 – returning full path

grep MODIFY /opt/releases/packages/cr666/sas/dbms/*/*;
/opt/releases/packages/cr666/sas/dbms/sti/FA_DISCLOSURE.ddl:MODIFY QUANTITY NUMBER;

I have found a solution, but I want to understand what is happening here. 1 command, different outcome/handling.

Best Answer

In your first example, the glob must have expanded to a single file. In that case, grep doesn't (by default) prepend the file name.

The second example must have expanded to several file names, and grep does prepend the filename in that case.

You can use the -H option to always get the filename prepended to the output, or -h to never get it.

If your grep lacks these options, you can use grep REGEX /path/to/pattern/* /dev/null to always get the filename (there's never any hit in /dev/null but it counts as a file name), or cat /path/to/pattern/* | grep REGEX to never get a filename.

Related Question