Skip to content


Awk oneliner to find a string in text files

If you want to know the name of files containing a special string, grep -c is your friend. But you also get names of files not containing your string (with count = 0). If you only want the names of files containing “mystring”, awk can help you:

grep -c "mystring" * | awk ' !/:0/ '

And if you don’t even want the number of times “mystring” appears (on 1 line):

grep -c "mystring" * | awk ' !/:0/ '| awk '{split($0, a, ":"); print a[1]}'

Any other ideas?

Possibly related posts: (automatically generated)

  1. How to remove files ending with ‘~’
  2. How many days without governement?
  3. Why did Sun chose Derby?
  4. I really like LaTeX Beamer
  5. GNU tools on MS-Windows

Posted in Computers, Work.

Tagged with , , , , .


3 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Philippe Teuwen says

    Your 2 awk calls can easily be grouped:
    | awk ‘ !/:0/{split($0, a, “:”); print a[1]}’
    or shorter, taking advantage of the natural capabilities of awk to parse a line, here we tell awk that our field separator is “:” :
    | awk -F: ‘ $2 != 0 {print $1}’
    which is equivalent to
    | awk -F: ‘ $2 {print $1}’

    But I kept the best for the end ;-)
    grep -r -l “mystring” .
    does the job, without awk :-)
    I prefer “-r .” which is recursing, rather than *
    -l is displaying the matching files, isn’t it what you wanted?

  2. Jean-Etienne says

    Thanks, Philippe. I really like the one you gave me via jabber:

    grep -c “mystring” * | grep -v “:0$”

  3. jaduks says

    Only the filename, no count,

    $ awk ‘/mystring/ {print FILENAME}’ * | sort | uniq
    $ awk ‘/mystring/ {print FILENAME}’ * | awk ‘ !x[$0]++’

    I liked the above “grep -r -l ” solution.
    http://unstableme.blogspot.com