Home > database >  grep a word and print this line and column 1, column 3 of next three line
grep a word and print this line and column 1, column 3 of next three line

Time:07-28

I have a text like this,

test to print 
1     aa    ee    0.000     0.000     0.000
2     bb    ff    0.000     0.000     0.000
3     cc    gg        0         0         0

I want to print out like below,

               1   2  3
test to print  ee ff gg

or just

test to print  ee ff gg

how to do that ?

CodePudding user response:

$ mygrep(){
   grep -A3 "$@" | awk '
      NR%4==1 { c1r2=$0; next }
      NR%4==2 { c2r1=$1; c2r2=$3; next }
      NR%4==3 { c3r1=$1; c3r2=$3; next }
      NR%4==0 { c4r1=$1; c4r2=$3
                printf " \t%s\t%s\t%s\n%s\t%s\t%s\t%s\n",
                             c2r1, c3r1, c4r1,
                       c1r2, c2r2, c3r2, c4r2
              }
   ' | column -t -s $'\t'
}

$ mygrep test <<'EOD'
test to print 
1     aa    ee    0.000     0.000     0.000
2     bb    ff    0.000     0.000     0.000
3     cc    gg        0         0         0
EOD
                1   2   3
test to print   ee  ff  gg

CodePudding user response:

I would harness GNU AWK for this task following way, let file.txt content be

test to print 
1     aa    ee    0.000     0.000     0.000
2     bb    ff    0.000     0.000     0.000
3     cc    gg        0         0         0

then

awk 'BEGIN{ORS="\t"}{print /test/?$0:$3}' file.txt

gives output

test to print   ee  ff  gg  

Explanation: I inform GNU AWK to use tab character as output record separator (ORS) that is when printing tab is used as last character rather than newline. Then for each line I print depending on test presence in said line, if it is present whole line ($0) otherwise 3rd column ($3). If you want to know more about ORS read 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR.

(tested in gawk 4.2.1)

  • Related