Linux shell command to reverse the field order of

2019-08-02 03:39发布

问题:

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

回答1:

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 :

$ 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 :

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


回答2:

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


回答3:

with bash:

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


回答4:

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