Skip to content

Instantly share code, notes, and snippets.

@louwersj
Created January 17, 2023 20:33
Show Gist options
  • Save louwersj/3268614b0b7b944f4beb6935ce67330d to your computer and use it in GitHub Desktop.
Save louwersj/3268614b0b7b944f4beb6935ce67330d to your computer and use it in GitHub Desktop.
BASH switch columns

You can use the command awk to manipulate columns in a file. To switch the first and second columns in a semicolon-delimited file, you can use the following command:

awk -F ';' '{print $2 ";" $1}' <input file> > <output file>

This command will read the input file, specifying the semicolon as the field separator (-F ';'), and for each line, print the second field ($2), followed by a semicolon, followed by the first field ($1). The output will be written to the specified output file.

If you want to change the file in place, you can use sed command as well.

sed 's/\(^[^;]*\);\(.*\)/\2;\1/' <input file> > <output file>

This command will search for lines starting with anything that is not a semicolon, followed by a semicolon, and capture that in the first group. Next it will capture the rest of the line in the second group. Then replace the whole line with the second group, followed by a semicolon, followed by the first group.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment