3

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
Neil
  • 345
  • 6
  • 14
  • Please add sample input and your desired output for that sample input to your question. – Cyrus Apr 09 '19 at 18:52

1 Answers1

2

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
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • It seems that the last result isn't caught in the `$match`. – Ali Tou Mar 02 '21 at 00:20
  • Looking at the answer provided [here](https://stackoverflow.com/a/12916758/8543203), appending a `|| [ -n "$match" ]` after `while read` fixed the issue above. – Ali Tou Mar 02 '21 at 00:24