Search code examples
pythonlinuxshellunixreverse

How to flip columns in reverse order using shell scripting/python


I need to reverse the order of columns in a dataset with 5 columns, putting the last column first and so on. How can I do this? Thanks!

data example:

1 2 3 4 5
6 7 8 9 0
3 4 5 2 1
5 6 7 2 3

I need output like as below:

5 4 3 2 1
0 9 8 7 6
1 2 5 4 3
3 2 7 6 5 

Solution

  • Perl to the rescue!

    perl -lane 'print join " ", reverse @F' < input-file
    
    • -n reads the file line by line, running the code specified after -e for each line
    • -l removes newlines from input and adds them to output
    • -a splits the input line on whitespace populating the @F array
    • reverse reverses the array
    • join turns a list to a string