Home > other >  how can i do reverse sorting using linux commands
how can i do reverse sorting using linux commands

Time:11-15

i have file.txt like this

word1 11 word11
w0rd2 23 woord22
wo7d3 44 wo-rd3
w07d4 78 wxrd44
w07d5 96 word5

It is necessary to use a script or command to make it look like this:

w07d5 11 word5
w07d4 23 wxrd44
wo7d3 44 wo-rd3
w0rd2 78 woord22
word1 96 word11

i try sort -k2,2nr file.txt it works, but I also change the column in the middle) maybe you can help me with something, I also know that AWK can work with the column specified in $, but I can't understand how to do it correctly

CodePudding user response:

Suggesting this simplified awk script:

script.awk

{ # read each line from input file, NR is internal variable `Number of Row`
  arr1[NR] = $1; # read column #1 into arr1
  arr2[NR] = $2; # read column #2 into arr2
  arr3[NR] = $3; # read column #3 into arr3
}
END { # post processing after reading input file.
  for (i = NR; i > 0; i--){ # reverse read the arrays from top to bottom
    print arr1[i], arr2[NR   1 - i], arr3[i]; # orderly output arr1, arr3, but reverse order arr2
  }
}

running:

awk -f script.awk input.txt

CodePudding user response:

This might work for you (GNU sort, sed and cat):

sort -k2,2n file |
sed -E 's/^\S  (\S ).*/s#\\S #\1#2/' |
cat -n |
sed -Ef - <(sort -k2,2nr file)

Sort column 2 of file in ascending order.

Extract column 2 and turn those values into a sed substitution script.

Apply line numbers to the above script.

Apply the script to the same file sorted by column 2 in descending order.


Same effect using paste:

paste <(sort -k2,2nr file) <(sort -k2,2n file) | 
sed -E 's/^(\S ) \S  (\S )\t\S  (\S ) .*/\1 \3 \2/'
  • Related