undocument find secret

Problem

You want to find a pattern in a file and have the line displayed.



Solution

I “discovered” this undocument (well in all the doco I’ve ever read), pretty much by accident.

Basically find produces a list of files (type f), in the current directory and supplies them individually to the grep command. Ordinarily if grep is supplied a single file, it just returns the pattern. You can suffix grep with -n to also return the line number and -l to return file names without the pattern.

But you cannot (AFAIK) force grep to return the filename and the pattern, from a list of files supplied by find. Of course you could use xargs, to produce a similar mechanism – but that is yet another process to fire up. 🙂

Also you could call a script, instead of grep – which uses something like sed to substitute the beginning of the line with filename – sed “s/^/$1: /” for example.

See the example.



Example


Anyway, I'm quite happy just using this little secret. 🙂 Having used it many times:

find . -type f -exec grep -i "pattern" {} /dev/null ;



Reference

[tags]find undocumented secret, Unix Coding School[/tags]



Leave a Reply

Your email address will not be published. Required fields are marked *