How to swap 2 columns in file content

In this article, we will see several command methods about how to swap two columns or fields in a text file.

Lets take the following file as example, the task is to swap the first 2 items of each line:
Linux, and, Life
Ubuntu, Kubuntu, Lubuntu
Arch, Debian, Fedora
Asus, Dell, Sony

1. Use awk

A simple command with awk to do the task is:
awk -F, ‘{print $2,$1,$3}’ OFS=, file

This command uses the print statement to print the fields in the desired order. The -F is to specify the input field separator and OFS for the output field separator. While this command is quite simple, it isnt suitable for a file with large number of fields since it forces us to print all columns individually.

 2. Another way with awk

 Here is a more complicated command with awk that can be used for a file with a large number of fileds.
awk -F, ‘BEGIN{OFS=FS;}{t=$i;$i=$j;$j=t;}1′ i=1 j=2 file

This command uses a temporary variable to swap the 2 fields. The two variables i and j contain the field numbers which are to be swapped. Just be setting the appropriate numbers in these 2 variables, any set of columns can be swapped. The 1 outside the braces prints every line by default.

3. Just with bash

while IFS=, read x1 x2 rest
> do
> echo ${x2},${x1},$rest
> done < file

This method uses the while command to parse the file. Since the IFS is set to comma, the read command will read till every comma. And by the same token, the first field will be assigned to x1, 2nd to x2 and the remaining to “rest” . While printing, echo first prints the 2nd followed by the 1st and then the rest.

4. Use perl

perl -F, -ane ‘BEGIN{$,=”,”;}($F[0],$F[1])=($F[1],$F[0]);print @F;’ file

This is a quite complicated command. Here we use the auto-split mode and comma as delimiter, every line is split into the special array @F. And by printing the entire array after swapping the entire array fields 0 & 1, we get the task done:

5. Use join

For files that have only a few fields, you can use the join command to swap 2 columns.

join -t, -o 1.2,1.1,1.3 file file

With this method, the input file is joined with itself which is done just to

Read more …

Comments are closed.