Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output grep results to text file, need cleaner output

Tags:

text

grep

output

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 
like image 924
user2398188 Avatar asked May 19 '13 04:05

user2398188


People also ask

How do I use grep in a text file?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.

How do you pipe a grep output?

grep is very often used as a "filter" with other commands. It allows you to filter out useless information from the output of commands. To use grep as a filter, you must pipe the output of the command through grep . The symbol for pipe is " | ".


2 Answers

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

like image 129
Nir Alfasi Avatar answered Oct 03 '22 14:10

Nir Alfasi


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.

like image 32
Ignacio Vazquez-Abrams Avatar answered Oct 03 '22 13:10

Ignacio Vazquez-Abrams