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 ...
source
share