-2

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 ?

Trung Võ
  • 5
  • 2
  • 1
    try a websearch on something like `bash awk pivot file` – markp-fuso Jul 27 '22 at 16:52
  • 3
    For inspiration you could have a look at this: https://stackoverflow.com/a/1729980/3593896 – Webber Jul 27 '22 at 16:52
  • There's not a single command to do what you want. You'll have to write some code. – Andy Lester Jul 27 '22 at 16:54
  • 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](https://stackoverflow.com/help/how-to-ask) 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 Jul 27 '22 at 17:59
  • 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 Jul 27 '22 at 19:12
  • if you are looking to `grep` on the string `test` ... would we also match on `retest` or `testing`? or do you want an exact (word) match? – markp-fuso Jul 27 '22 at 19:14

2 Answers2

0
$ 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
jhnc
  • 11,310
  • 1
  • 9
  • 26
0

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)

Daweo
  • 31,313
  • 3
  • 12
  • 25