Linux shell command to reverse the field order of

2019-08-02 03:54发布

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

4条回答
Deceive 欺骗
2楼-- · 2019-08-02 04:23

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
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-02 04:41

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
查看更多
等我变得足够好
4楼-- · 2019-08-02 04:44

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
查看更多
\"骚年 ilove
5楼-- · 2019-08-02 04:45

with bash:

while read -ra words; do 
    for ((i=${#words[@]}-1; i>=0; i--)); do 
        printf "%s " "${words[i]}"
    done
    echo
done < file
查看更多
登录 后发表回答