Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort the line of a file by to the second word from the end

I want to sort the line accorfing to the last number just before the space. And this is a simplified example:

c3_abl_eerf_14 sasw
a.bla_haha_2 dnkww
s.hey_3 ddd

And this is the results I want:

a.bla_haha_2 dnkww
s.hey_3 ddd
c3_abl_eerf_14 sasw

I don't know how to do this, maybe by the command sort? And, sometimes I used the sort command, it may wrongly treat the 14 less than 2, I don't want this to happen.

like image 239
spring cc Avatar asked Jun 08 '16 08:06

spring cc


1 Answers

this command chain works for your example:

sed -r 's/.*_([0-9]+) .*/\1 &/' file|sort -n|sed 's/[^ ]* //'

The idea is

  • extract the number first, add to the beginning of the line
  • sort all lines by this number
  • remove the number

update

sort by last number in the line, no matter where the number is:

awk -F'[^0-9]+' '{$0=(length($NF)?$NF:$(NF-1)) OFS $0}7' file|sort -n|sed 's/[^ ]* //'
like image 50
Kent Avatar answered Sep 19 '22 20:09

Kent