Home > Back-end >  How to sort data in linux by bash scripting from last to first
How to sort data in linux by bash scripting from last to first

Time:10-04

How to sort data in text file in linux by command in console from last to first?

I have got:

1:a k2:b k3:c k

and i need:

k k3:c k2:b 1:a

CodePudding user response:

Assuming the sample input is in a variable:

$ x='1:a k2:b k3:c k'

One idea to reverse the direction of the space-delimited values:

$ tr ' ' '\n' <<< "${x}" | tac | tr '\n' ' '
k k3:c k2:b 1:a

Another idea using a bash/for loop:

$ unset pfx y
$ for i in ${x}            # do not wrap ${x} in double quotes since we DO want word splitting to occur
do
    y="${i}${pfx}${y}"
    pfx=" " 
done
$ echo "${y}"
k k3:c k2:b 1:a

Another idea using awk:

$ awk '{for (i=NF;i>=1;i--){printf "%s%s",pfx,$i;pfx=" "};printf "\n"}' <<< "$x"
k k3:c k2:b 1:a
  • Related