Outputting empty lines between grep results when working with -C (or -B / -A)

Consider the following grep command above the input of this toy:

user@user:~$ echo -e "a\nb\nc\nd\ne" | egrep "(b|d)" -C 1 -n
1-a
2:b
3-c
4:d
5-e

Although this is already good, as it was, I was wondering if there was any trick to get an empty string between different results. Something similar to:

user@user:~$ echo -e "a\nb\nc\nd\ne" | egrep "(b|d)" -C 1 -n
1-a
2:b
3-c

3-c
4:d
5-e

Whether there is a?

thank

+4
source share
1 answer

No, you cannot do this with grep. You can do this with awk:

$ echo -e "a\nb\nc\nd\ne" | awk -v c=1 '{a[NR]=$0} /(b|d)/{hits[NR]} END{ for (hit in hits) { if (x++) print "---"; for (i=hit-c;i<=hit+c;i++) print i (i==hit?":":"-") a[i] } }'
1-a
2:b
3-c
---
3-c
4:d
5-e

Obviously, this type of length is every time you want to do this, but you can use it in a shell script, for example:

$ cat markRanges
awk -v c="$1" -v re="$2" '
{ a[NR]=$0 }
$0 ~ re { hits[NR] }
END {
    for (hit in hits) {
        if (x++) {
            print "---"
        }
        for (i=hit-c; i<=hit+c; i++) {
            print i (i==hit?":":"-") a[i]
        }
    }
}
'

$ echo -e "a\nb\nc\nd\ne" | ./markRanges 1 '(b|d)'
1-a
2:b
3-c
---
3-c
4:d
5-e

Massage suitable ...

+2
source

Source: https://habr.com/ru/post/1651172/


All Articles