Linux shell command to reverse the field order of varying length text records

筅森魡賤 提交于 2020-01-15 10:16:13

问题


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


来源:https://stackoverflow.com/questions/21944796/linux-shell-command-to-reverse-the-field-order-of-varying-length-text-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!