Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash sort list of strings by number at the end

Tags:

bash

sorting

I have a list of files with a version number at the end that I need to sort

/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9

when I pipe it through grep it sort like so:

echo $files | sort -n
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9

I think the -n is getting confused by the first number in the file name.

How can I sort it numerically by the last number

like image 628
Sam Brinck Avatar asked Jun 05 '13 16:06

Sam Brinck


1 Answers

Kaizen ~/so_test $ cat ztestfile1 | sort -t'/' -n -k10
/this/is/a/file/path/product-2.0/file/name/6
/this/is/a/file/path/product-2.0/file/name/7
/this/is/a/file/path/product-2.0/file/name/8
/this/is/a/file/path/product-2.0/file/name/9
/this/is/a/file/path/product-2.0/file/name/10
/this/is/a/file/path/product-2.0/file/name/12
/this/is/a/file/path/product-2.0/file/name/13

does this help ?

alternative way ie to be independent from the position .....

 Kaizen ~/so_test  $ cat ztestfile1 | sort -V
 /this/is/a/file/path/product-2.0/file/name/6
 /this/is/a/file/path/product-2.0/file/name/7
 /this/is/a/file/path/product-2.0/file/name/8
 /this/is/a/file/path/product-2.0/file/name/9
 /this/is/a/file/path/product-2.0/file/name/10
 /this/is/a/file/path/product-2.0/file/name/12
 /this/is/a/file/path/product-2.0/file/name/13

please note its a -V (Capital) option in sort that looks into numeric differences in a string to sort ..... like in version number .

man page text ::

   -V, --version-sort
          natural sort of (version) numbers within text
like image 166
AppleBee12 Avatar answered Oct 05 '22 06:10

AppleBee12