Neil
Neil

Reputation: 395

Iterate over grep output in multi-line chunks

I can't figure out how to iterate by match from grep output when using -A or -B flags (returning multiple lines for a single match). I'm not opposed to using awk for this, but this will be used to check multiple large files so the shorter execution time, the better.

I figured I could achieve this by using --group-separator flag of grep and setting IFS to the same character, but this doesn't seem to be the case.

$ grep --group-separator=@ -B2 'locked' thisisatest | while IFS=@ read -r match; do 
echo "a" 
echo "${match}"
done
a
this is a test file asdflksdklsdklsdkl.txt
a
this is meaningless
a
this is locked
a

a
this is a test file basdflksdklsdklsdkl.txt
a
this is meaningless
a
this is locked

$ cat thisisatest
this is a test file asdflksdklsdklsdkl.txt
this is meaningless
this is locked
j
j
j
j
j
this is a test file basdflksdklsdklsdkl.txt
this is meaningless
this is locked

I expect "a" to be printed before and after the entirety of a match such as:

a
this is a test file asdflksdklsdklsdkl.txt
this is meaningless
this is locked
a

Upvotes: 3

Views: 1526

Answers (1)

John Kugelman
John Kugelman

Reputation: 361605

Changing $IFS controls how read splits a line into fields. You're only having it fill out one field at a time ($match), so the field delimiter doesn't matter. Change the line delimiter instead: use read -d.

grep ... | while read -d@ -r match; do

Upvotes: 2

Related Questions