grep command to add end line after every match [du

2019-03-16 05:24发布

This question already has an answer here:

do you have any idea how to add some end line like

"=========================================================================================="

after every match

tail -f error.log -n 2000 | grep -B 10 -A 25 'Exception:'

this command prints all Exceptions log but i likes to see one seperator line for each exception log.

4条回答
对你真心纯属浪费
2楼-- · 2019-03-16 05:27

I prefer sed for text manipulation:

# cat test 
1
Exception
2
Exception
3
4
Exception
5
Exception
6
7
8
Exception
9



# sed -i '/Exception/a =========================' test 


# cat test 
1
Exception
=========================
2
Exception
=========================
3
4
Exception
=========================
5
Exception
=========================
6
7
8
Exception
=========================
9
查看更多
迷人小祖宗
3楼-- · 2019-03-16 05:29

You posted a command that doesn't do what you want and described it's output, but you didn't tell us what you DO want so this is a guess but maybe it'll be useful. It prints the 2 lines before and 3 lines after some regexp:

$ cat file
a
b
c
d
FOO
e
f
g
h
i
j
FOO
k
l
m
n
o

$ awk -v re="FOO" -v b=2 -v a=3 'NR==FNR{line[FNR]=$0;next} $0 ~ re{for (i=(FNR-b);i<=(FNR+a);i++) print line[i]; print "=====" }' file file
c
d
FOO
e
f
g
=====
i
j
FOO
k
l
m
=====
查看更多
不美不萌又怎样
4楼-- · 2019-03-16 05:30

For people like myself who have a 'very old' grep that doesn't include the --group-separator option, the following seems to be an acceptable workaround.

Noticing that grep (my version, 2.5.1) does produce a "small, default" separator between groups (--), you can easily replace that string with a string of your choice:

tail -f rms.log -n 2000 | grep -B 10 -A 25 'Exception:' | sed 's/^--$/=================/'

This does replace the -- with ============

Obviously you can modify this to your liking. If you have the option of using --group-separator (@sudo_O's answer) that is obviously preferable.

EDIT reading the comments below the question, I realize that when @starrify updated his comment (which I had not noticed before) his comment essentially pointed directly to this solution - so I feel I own him a tip of the hat...

查看更多
神经病院院长
5楼-- · 2019-03-16 05:43

You want the following option:

--group-separator=SEP
Use SEP as a group separator. By default SEP is double hyphen (--).

Demo:

$ cat file
before
exception 1
after
foo
bar
before
exception 2
after

$ grep -A 1 -B 1 --group-separator======================== exception file 
before
exception 1
after
=======================
before
exception 2
after
查看更多
登录 后发表回答