Find secrets – undocumented feature

Problem

You want to find a pattern in a files, but have the file name and pattern printed.

If you run find . -type f -exec grep -i “pattern” {} ; it will only show the pattern turning up – i.e not the file name as well.

If you run find . -type f -exec grep -il “pattern” {} ; it will only show the file name turning up – i.e not the line containing the pattern as well! 🙂



Solution

Maybe you have seen this solution before, but AFAIK it is completely undocumented.

I discovered it whilst trying to do this very thing and I just thought, hmmm … I wonder. 🙂



Example


To force grep to print the line containing the pattern and the file name, we pass /dev/null as another argument. Find sees this as multiple arguments, so prints the file name and line containing pattern.

  • The normal basic find

  • $ find . -type f -exec grep -i author {} ;

    <ADDRESS CLASS="doc-author">The OpenLDAP Project <<A target=_blank HREF="http://www.openldap.org/">http://www.openldap.org/</A>></ADDRESS>
    <META name="Author" content="TechRock">
    <META HTTP-EQUIV="AUTHOR" content="TechRock">

  • find looking for just the file name

  • $ find . -type f -exec grep -il author {} ;

    ./cs/ldap-head.inc
    ./meta.inc

  • Undocumented feature, print file name and line content

  • $ find . -type f -exec grep -i author {} /dev/null ;

    ./cs/ldap-head.inc:<ADDRESS CLASS="doc-author">The OpenLDAP Project <<A target=_blank HREF="http://www.openldap.org/">http://www.openldap.org/</A>></ADDRESS>
    ./meta.inc:<META name="Author" content="TechRock">
    ./meta.inc:<META HTTP-EQUIV="AUTHOR" content="TechRock">



Reference

[tags]unix find, find undocumented features, find secrets, Unix Coding School[/tags]



Leave a Reply

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