[英]Outputting empty lines between grep results when running it with -C (or -B / -A)
在這個玩具輸入上考慮以下grep命令:
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
雖然這已經很好了,但我想知道是否有某種技巧可以在不同結果之間找到一條空行。 類似於:
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
在那兒?
謝謝
不,你不能用grep這樣做。 你可以用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
很明顯,每次你想要這樣做都有點長,但你可以在shell腳本中使用它,例如:
$ 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
按摩適合......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.