0

Given a text file file.txt, transpose its content.

For example, if file.txt has the following content:

name age
alice 21
ryan 30

Output the following:

name alice ryan
age 21 30
choroba
  • 231,213
  • 25
  • 204
  • 289
Neeld
  • 503
  • 1
  • 4
  • 10

1 Answers1

0

With shell utils cut and paste:

for f in 1 2 ; do cut -d ' ' -f $f file.txt ; done | paste -d ' ' - - -

Outputs:

name alice ryan
age 21 30

How it works. The field separator in file.txt is a space, so both cut and paste (which have tab as a default field separator) must use the -d ' ' option. We know in advance there are two columns in file.txt, the for loop therefore requires two passes. Pass #1, cut selects column 1 from file.txt, pass #2, column 2. When the for loop ends, what's fed to the pipe '|' looks like:

name alice ryan age 21 30

Then paste outputs that three at a time (hence the three hyphens).

agc
  • 7,973
  • 2
  • 29
  • 50
  • Thanks agc this also works but looks like cut and paste re-arranges words vs. awk parses and uses logic to do it? I am trying to learn as a new programmer, most efficient way to do it.Thnx. – Neeld Apr 10 '16 at 12:17
  • @Neeld, see revised answer above with explanation. – agc Apr 10 '16 at 17:06
  • Perfect . checking man pages of cut and paste .Thanks again. – Neeld Apr 11 '16 at 08:33