Search code examples
awksedswaptabular

AWK: Need to swap values between two columns if the left one is smaller than the right one


So what I've got so far is a Bed-Table file and the problem with this file is, that in some rows the value in column 2 is bigger than the value in column 3.

Is there any one liner in awk, which would swap these two values, so that the table always got the smaller value in col 2 and the bigger one in col 3?

chr01    100    200
chr02    300    150 

so in this example the desired output would be:

chr01    100    200
chr02    150    300 

Solution

  • Just swap the columns if they're in the wrong order, using a temporary variable:

    $ awk '$2 > $3 { temp = $3; $3 = $2; $2 = temp } 1' OFS='\t' file
    

    1 at the end is a common shorthand for {print}, so each line is printed. Setting the output field separator OFS to a tab character preserves the format.

    Alternatively:

    $ awk -F'\t' '$2 > $3 { $0 = $1 FS $3 FS $2 } 1' file
    

    Rearrange the contents of the line if necessary, using the input field separator FS which has been set to a tab character.