Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over grep output in multi-line chunks

Tags:

linux

grep

bash

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
like image 244
Neil Avatar asked Feb 04 '26 19:02

Neil


1 Answers

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
like image 134
John Kugelman Avatar answered Feb 06 '26 09:02

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!