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=4 provide amount of lines header has (header) , how many lines after match should printed (n).
  • /process: 2/{c=n+1} when process: 2 line seen, set variable c (from counter).
  • c&&c-- evaluate c. if value bigger 0, evaluates true, line printed. also, decrement value n lines printed.
  • nr<=header if line number equal or lower given value header, evaluates true , line printed.

Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

How to provide Authorization & Authentication using Asp.net, C#? -

How to use Authorization & Authentication in Asp.net, C#? -