Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing two fields in awk

Tags:

awk

Suppose that a file looks like:

a|b|c|d
a|b|c|d
...
a|b|c|d

How do I transpose two fields, for example:

c|b|a|d
c|b|a|d
...
c|b|a|d

Thanks in advance!

like image 574
Russell Avatar asked Feb 23 '23 17:02

Russell


2 Answers

Here is another solution: swap the first and third field, then print:

awk -F '|' '{ temp=$1; $1=$3; $3=temp; print }' data.txt
like image 108
Hai Vu Avatar answered Mar 05 '23 17:03

Hai Vu


At least if memory serves, something on this general order should work:

BEGIN { FS="|"; }

    { printf("%s|%s|%s|%s\n", $3, $2, $1, $4); }
like image 32
Jerry Coffin Avatar answered Mar 05 '23 18:03

Jerry Coffin