Output grep results to text file, need cleaner output
Solution 1
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
Solution 2
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.
Solution 3
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
user2398188
Updated on January 14, 2022Comments
-
user2398188 over 2 years
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
-
Crista23 about 10 yearsDoes grep write only when it finishes or does it write line by line as it processes the content? Thanks!
-
GTodorov over 9 years@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?
-
Nir Alfasi over 9 years@GTodorov yes, if you want to append use
>>
-
HBeel over 7 yearsFor future visitors the answer to @Crista23's question is it writes when the grep has finished