Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I find a string in files in a directory, using file names beginning with the letter a. I also want to get the number of occurrences of this string from the grep I run.

I tried this

cat * | grep -c string but it searches all files. I just want to search files that begin with letter a

share|improve this question

migrated from Apr 30 '10 at 2:15

This question came from our site for professional and enthusiast programmers.

Note also that grep -c does not give you the number of occurrences... It gives you the number of lines that match. So if you have a line that says "stringstring", that will count as 1, not 2. – asveikau Apr 29 '10 at 21:51
grep -c string a*
share|improve this answer
Thanks. Can we have it display the files that it displays with results date wiese like when we do ls -ltrh. Can we add that kind of parameters as well? – Anonymous Apr 29 '10 at 21:43

grep -c string a*

share|improve this answer

alternative method giving you the power and flexibility of the 'find' command:

find . -name "a*" | xargs grep -c string

share|improve this answer
my version: find . -type f -iname foo* -print | xargs egrep -i your_regex – woohoo Jan 10 '13 at 16:12

grep -c string a*

share|improve this answer

As the others have said, your basic solution is:

grep -c string a*

You said you wanted to sort the files and list extra info.

You can't get all of that with grep, but have ls do part of it if you're not worried about efficiency and the files don't have spaces or other weird characters:

ls -tr `grep -l string a*` | while read file; do
    grep -c string "$file" | tr '\n' '\t'
    ls -l "$file"

The first grep in the backticks searches for matching files, listing only the names. The first ls then sorts those by modification time in reverse. We then search through each file a second time to count occurrences, and prepend the count to the standard "ls -l" listing.

This will be slow; if you really need a faster version you can probably hack one up in a scripting language.

share|improve this answer

You must log in to answer this question.