Sorting a file with integer in parentheses with no space

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?

Asked By: roygvib

||

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.

Answered By: heemayl

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
Answered By: steve
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.