Monday, December 8, 2008

Swapping two columns in a file - awk


Input file:

$ cat draft.txt
C1:C2:C3:C4:C5:C6
1:1:1:1:1
2:4:8:16:32
3:9:27:81:243

Required: I had to swap 2nd column with 5th column and print the output file. This is how we can do using awk in bash.

$ awk 'BEGIN {FS=OFS=":"} {temp=$2; $2=$5; $5=temp} {print}' draft.txt

Output:

C1:C5:C3:C4:C2:C6
1:1:1:1:1
2:32:8:16:4
3:243:27:81:9

** This may not make more sense for small files (i.e. files with say 4-5 fields as you can always print $1,$5,$2,...), but for files with more number of fields or columns, this is really helpful.

Similar post:

- Remove or delete column using awk

No comments:

© Jadu Saikia www.UNIXCL.com