Reputation: 2881
I have a string that I'm grepping for in my directory that looks like this:
Found an error with id: XXXX
I want to be able to take all those lines and write them to a new separate file. Currently I have this:
grep -rl "Found an error with id:" . >> errorOutput.txt
but that only prints which file contains that string. Any way I could get the full line with the id?
Upvotes: 1
Views: 1112
Reputation: 85693
Your -l
flag is the culprit here. It suppresses the contents in the matched lines and just prints out the files containing the match because of the -r
recursive search. Even without the -l
flag you get a filename:pattern
result.
So to just store the patterns in the file, use an extra awk
to the pipeline as below.
grep -r "Found an error with id:" . | awk -F: '{ print $2 }' > results.log
Or with just grep
just skip printing the filenames with the -h
flag ( both FreeBSD and GNU variants support this )
grep -rh "Found an error with id:" . > results.log
and BTW awk
is powerful in itself, it can do pattern search by itself on the file system. So you could do
awk '/Found an error with id:/' * > results.log 2>/dev/null
Upvotes: 1