Question

I would like a command line incantation to reverse the field order of arbritrary length text records. Solutions provided in Rearrange columns using cut and Elegant way to reverse column order don't solve this issue since they assume a fixed amount of fields, though maybe they would with minor changes.

Sort of like the tac command that exhibits reverse cat functionality. I'd like what the ohce command would do (if it existed) to reverse echo functinality.

For example:

a b c d
e f
g h i

Should be transformed to

d c b a
f e
i h g
Was it helpful?

Solution 2

There's a command to do it, it's named rev from util-linux :

$ rev file
d c b a
f e
i h g

or using :

$ perl -lane 'print join " ", reverse @F' file
d c b a
f e
i h g

But like you explain in the comments, if you want the 3 latest columns, you can use :

awk '{print $(NF-2), $(NF-1), $NF}' file

OTHER TIPS

Using awk:

awk '{for (i=NF; i>1; i--) printf "%s%s", $i, FS; print $i }' file
d c b a
f e
i h g

with bash:

while read -ra words; do 
    for ((i=${#words[@]}-1; i>=0; i--)); do 
        printf "%s " "${words[i]}"
    done
    echo
done < file

Using datamash:

echo 'a b c d
e f          
g h i' | datamash --no-strict -t' ' reverse

Output:

d c b a
f e
i h g

Unlike rev, it doesn't reverse words:

echo 'abc xyz' | datamash --no-strict -t' ' reverse

Output:

xyz abc
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top