Tutorial :Using grep to find a string in files



Question:

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


Solution:1

grep -c string a*  


Solution:2

grep -c string a*


Solution:3

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

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


Solution:4

grep -c string a*


Solution:5

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"  done  

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »