I'm on RHEL 6 using BASH.

I'm trying to sort some lines in a file, by a number that is embedded in a field. The name of the file is word.txt.

This is the command I am using:

sort -n -k4 word.txt

This is the output I am getting, not in numerical order:

INSERT INTO area_names VALUES(124,'NewYork');
INSERT INTO area_names VALUES(125,'NewYork');
INSERT INTO area_names VALUES(12,'NewYork');

Obviously, the line with just "12" should be first.

The number after "VALUES(" can be of any length

How can I tell sort to sort on the number in between "VALUES(" and "," ?

I can fall back on a workaround of putting a white space after "VALUES(" in the data, but I would rather not do that unless that is the best option.


Try this:

 sort -t "(" -k2,2 -n word.txt


INSERT INTO area_names VALUES(12,'NewYork');
INSERT INTO area_names VALUES(124,'NewYork');
INSERT INTO area_names VALUES(125,'NewYork');

-k POS1[,POS2]

     Specify a sort field that consists of the part of the line between
     POS1 and POS2 (or the end of the line, if POS2 is omitted),

     Each POS has the form `F[.C][OPTS]', where F is the number of the
     field to use, and C is the number of the first character from the
     beginning of the field.  Fields and character positions are
     numbered starting with 1; a character position of zero in POS2
     indicates the field's last character.  If `.C' is omitted from
     POS1, it defaults to 1 (the beginning of the field); if omitted
     from POS2, it defaults to 0 (the end of the field).  OPTS are
     ordering options, allowing individual keys to be sorted according
     to different rules; see below for details.  Keys can span multiple

     Example:  To sort on the second field, use `--key=2,2' (`-k 2,2').
  • It works. Thank you. What is happening with the ",2" in -k2,2 ? The MAN page doesn't say much about that. – user787832 Mar 11 '15 at 13:55
  • I've added text from info sort. – Cyrus Mar 11 '15 at 20:49
  • Thanks, I just used the manpage and "info" didn't occur to me – user787832 Mar 12 '15 at 19:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.