Skip to content
Advertisement

Swap two columns depending on condition for third column in linux

I have a file with 3 columns like this

  Col1         Col2          Col3 
   A            B             <-
   C            D             ->
   E            F             ->

I want to swap the entries of the Col1 and Col2 whenever there is

<-

in the third column. I want my output file to be like

 Col1         Col2          Col3 
   B            A             ->
   C            D             ->
   E            F             ->

Advertisement

Answer

awk '($3=="<-"){$3=$2;$2=$1;$1=$3;$3="->"}1' <file>

Essentially, if $3=="<-", then swap the columns and redefine $3. Then print.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement