简体   繁体   中英

how can I grep a directory and write the full line found to a file

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM