Search code examples
linuxawksedcut

Swap columns of a file - Linux (exact position, not word)


I would like to know how to swap columns (the exact character) of a file with Linux (using cut, awk, sed or whatever you can help me with). I have seen how to swap a whole expression (using delimiters) and whole words.

Example:

128934
38 2008

Swapping column 3 with 5:

123984
3802 08

Another way to ask this, would be swap the 3rd char of each row with the 5th.


Solution

  • A bit unwieldy, with sed:

    $ sed -E 's/^(..)(.)(.)(.)/\1\4\3\2/' infile
    123984
    3802 08
    

    This captures the first five characters of each line in four groups and then rearranges them. -E is just there for convenience; without it, we have to escape the parentheses as in \(.\).