Bash: How to Swap Two Columns in a File


Often you may want to use Bash to swap two columns in a file.

You can use the following syntax with awk to do so:

awk ' { x = $2; $2 = $4; $4 = x; print; } ' player_stats.txt

This particular example will swap columns 2 and 4 in the text file named player_stats.txt.

Here is how this syntax works:

  • First, we create a variable named x (you can name this anything you want) to be equal to the values in column 2 of the file
  • Then, we assign the values from column 4 to be used as the values for column 2
  • Lastly, we assign the values from the variable x (which contains the values in column 2) to be used as the values for column 4

By using this syntax, we are able to swap columns 2 and 4 in the file while leaving all other columns in the same positions.

The following example shows how to use this syntax in practice.

Example: Use Bash to Swap Two Columns in a File

Suppose that we have a file named player_stats.txt that contains information about various basketball players.

We can use the cat command to view the contents of this file:

Suppose that we would like to swap columns 2 and 4 in the file.

We can use the following syntax to do so:

awk ' { x = $2; $2 = $4; $4 = x; print; } ' player_stats.txt

The following screenshot shows how to use this syntax in practice:

Bash swap columns

Notice that columns 2 and 4 in the file have been swapped.

All other columns in the file have remained in the same positions.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Delete Duplicate Lines in File
Bash: How to Replace All Occurrences of String in File
Bash: How to Replace Specific Line in File

Leave a Reply