linux - Grep a pattern and also print the header of the file -
i have file contains information following:
header info line 1 header info line 2 header info line 3 .... process: 1 info 1 info 2 info 3 process: 2 info 1 info 2 info 3 process: 3 info 1 info 2 info 3 what want grep 1 of process lines (e.x "process: 2") delete other process while keeping header information. know number of lines after "process: #" (lets use 3 example). don't know how many process numbers there are. trying was:
grep "process: 2" -a 3 file.txt however lose header information. want keep header info rid of other process info. feel can egrep i'm not sure how.
my desired output following:
header info line 1 header info line 2 header info line 3 .... process: 2 info 1 info 2 info 3
better use awk this:
$ awk -v n=3 -v header=4 '/process: 2/{c=n+1} nr<=header || c&&c--;' file header info line 1 header info line 2 header info line 3 .... process: 2 info 1 info 2 info 3 this uses printing sed or awk line following matching pattern check on lines on header.
explanation
-v n=3 -v header=4provide amount of lines header has (header) , how many lines after match should printed (n)./process: 2/{c=n+1}whenprocess: 2line seen, set variablec(from counter).c&&c--evaluatec. if value bigger0, evaluates true, line printed. also, decrement valuenlines printed.nr<=headerif line number equal or lower given valueheader, evaluates true , line printed.
Comments
Post a Comment