11

I am trying to sort a file like this (which is a list of subroutine names)

cfn=(1370) __lib_file_MOD_file_open
fn=(1368) __universe_MOD_general_boot
fn=(916) __universe_MOD_general_main
fn=(6142) __grid_var_MOD_get_overlap
...

according to the integer inside parentheses. I first tried the sort command as

sort -t '=' -k 2 routine_list.txt

but then fn=(916) comes at the end of the ouput.

fn=(1368) __universe_MOD_general_boot
cfn=(1370) __lib_file_MOD_file_open
fn=(6142) __grid_var_MOD_get_overlap
...
fn=(916) __universe_MOD_general_main

but I would like the numbers to be sorted in the increasing order (916 -> 1368 -> 1370 -> ...) Is it possible to do this relatively simply by using several commands or options?

roygvib
  • 345

2 Answers2

12

How about:

sort -nt'(' -k2 file.txt

Test :

$ sort -nt'(' -k2 file.txt 
fn=(916) __universe_MOD_general_main
fn=(1368) __universe_MOD_general_boot
cfn=(1370) __lib_file_MOD_file_open
fn=(6142) __grid_var_MOD_get_overlap
  • -n indicates we are sorting numerically

  • t'(' sets the delimiter as (

  • -k2 sets the key to sort as the second field i.e. starting from the digits to the end of the line.

heemayl
  • 56,300
  • oooooh attaching -n works... I read the man page and tried -n before, but it didn't work at that time... but now the above combination works perfectly. Thanks very much :) – roygvib Jul 11 '15 at 19:48
  • @roygvib i would suggest you to use ( as the delimiter instead of = as if you use ( then sorting can start numerically from the very starting point of the second field.. – heemayl Jul 11 '15 at 19:51
  • Yes, it should be better to use '(' than '='. I remember I tried using both '(' and ')' as delimiters simultaneously but no success and gave up using parentheses at that time... – roygvib Jul 11 '15 at 19:58
6

Try this. Sets the delimiter to =, and then uses field 2 from character 2 onwards (ignoring the "(").

sort -t= -k 2.2n file.txt
fn=(916) __universe_MOD_general_main
fn=(1368) __universe_MOD_general_boot
cfn=(1370) __lib_file_MOD_file_open
fn=(6142) __grid_var_MOD_get_overlap

Or even

sort -t\( -k 2n <foo
fn=(916) __universe_MOD_general_main
fn=(1368) __universe_MOD_general_boot
cfn=(1370) __lib_file_MOD_file_open
fn=(6142) __grid_var_MOD_get_overlap
steve
  • 21,892
  • 1
    hmm.. this also works as expected. It is nice to know that some characters can be skipped. Thanks very much :) – roygvib Jul 11 '15 at 20:00