1
votes

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 ?

2
try a websearch on something like bash awk pivot file - markp-fuso
For inspiration you could have a look at this: stackoverflow.com/a/1729980/3593896 - Webber
There's not a single command to do what you want. You'll have to write some code. - Andy Lester
SO is not a code writing service; you're expected to show your effort (eg, research, code); consider reviewing how do I ask a good question and then come back and update the question accordingly; in particular, show the code you've tried and the (wrong) output generated by your code - markp-fuso
what string are you attempting to grep on? what happens if there are multiple lines with matches ... process all matches? process just the first match? and what happens if there's an overlap (eg, every other line has a grep match)? - markp-fuso

2 Answers

0
votes
$ 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
0
votes

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)