Output grep results to text file, need cleaner output

user2398188 picture user2398188 · May 19, 2013 · Viewed 311k times · Source

When using the Grep command to find a search string in a set of files, how do I dump the results to a text file?

Also is there a switch for the Grep command that provides cleaner results for better readability, such as a line feed between each entry or a way to justify file names and search results?

For instance, a away to change...

./file/path: first result
./another/file/path: second result
./a/third/file/path/here: third result

to

./file/path: first result

./another/file/path: second result

./a/third/file/path/here: third result

Answer

Nir Alfasi picture Nir Alfasi · May 19, 2013
grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post