Linux shell命令扭转的不同长度的文本记录中的字段顺序(Linux shell comman

2019-10-19 10:10发布

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

Answer 1:

有一个命令来做到这一点,它的命名rev从UTIL-Linux的 :

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

或使用perl的 :

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

但是,像你在评论中解释,如果你想在3列最新的,您可以使用AWK :

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


Answer 2:

用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


Answer 3:

使用bash:

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


Answer 4:

使用datamash

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

输出:

d c b a
f e
i h g

不像rev ,它不扭转的话:

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

输出:

xyz abc


文章来源: Linux shell command to reverse the field order of varying length text records