Wednesday, November 21, 2012

Transpose using UNIX paste command


I have already posted about performing transpose of a matrix using Awk in my earlier posts post1 and post2 . This example shows a not so efficient way of achieving the same.

Input file:
$ cat file.txt 
 PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND                                                                                                                                                                      
32420 testuser 20   0 1219m 969m  49m R   34 12.1   1043:14 worker
Required output:
PID 32420
USER testuser
PR 20
NI 0
VIRT 1219m
RES 969m
SHR 49m
S R
%CPU 34
%MEM 12.1
TIME+ 1043:14
COMMAND worker
$ for i in $(seq 12); do awk -v X=$i '{print $X}' file.txt | paste - - ; done
Related posts:
- How to access external variable in Awk and SED
- Generate bash loop arguments using seq command
- UNIX seq command format option example
- Some good usage of UNIX paste command
- Compare two numeric fields of two files in Bash

3 comments:

Kamaraju Kusumanchi said...

This is great! I have been looking for something like this for a long time. Thanks for sharing it.

awkseeker said...

Hi! I have inversely quest. I want to convert from Horizontal to Vertical. infile
info1=1
info2=a,s
info3=d
info1=2,3
info2=s
info3=d,s
info1=4
info2=s
info3=3

outfile
1|a,s|d
2,3|s|d,s
4|s|3

Please advise.

Sincerely

awkseeker said...

hi, please help

infile
info1=1
info2=a,s
info3=d
info1=2
info2=d
info3=d,s

outfile
1|a,s|d
2|d|d,s

© Jadu Saikia www.UNIXCL.com