117

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
ruffin
  • 16,507
  • 9
  • 88
  • 138
user2398188
  • 1,417
  • 3
  • 12
  • 12
  • 24
    I love that these actual super helpful "not a real question" questions have ended up being in the top search results in Google years later. – Adrian Carr Nov 05 '18 at 19:57

3 Answers3

149
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 in this post

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • 11
    Does grep write only when it finishes or does it write line by line as it processes the content? Thanks! – Crista23 Feb 19 '14 at 17:51
  • 6
    @alfasin - isn't the single '>' going to overwrite the results in the output file? Shouldn't we use double '>>' in order to append the results into to the file? – GTodorov Nov 24 '14 at 16:52
  • 3
    @GTodorov yes, if you want to append use `>>` – Nir Alfasi Nov 24 '14 at 17:21
  • 20
    For future visitors the answer to @Crista23's question is it writes when the grep has finished – HBeel Sep 22 '16 at 13:06
45

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

To add a blank line between lines of text in grep output to make it easier to read, pipe (|) it through sed:

grep text-to-search-for file-to-grep | sed G
Mike
  • 1,080
  • 1
  • 9
  • 25
dan
  • 41
  • 1