Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I have a number of files with names like:

beginning_num1_734_num2_1.363e+12_num3_800.pdf
beginning_num1_735_num2_7.453e+13_num3_800.pdf
beginning_num1_1007_num2_9.453e+12_num3_1200.pdf

I'd like to be able to sort a list of these filenames by the various nums, and pass the sorted list to various command line utilities. For example, if I were sorting by num2, I'd want the order:

beginning_num1_734_num2_1.363e+12_num3_800.pdf
beginning_num1_1007_num2_9.453e+12_num3_1200.pdf
beginning_num1_735_num2_7.453e+13_num3_800.pdf

I have a python script to do this, but it seems like it should be possible with nothing but filters like sed and sort.

Is there any easy way to sort by parts of a file name, using only common command line filters?

share|improve this question
    
I think the trick can be done in awk, are + _ and . the only valid separators in this case? –  vfbsilva Aug 16 '13 at 20:43
    
@vfbsilva: + isn't a separator, num2 is a floating point number. –  Dan Aug 16 '13 at 20:48
    
please point expected input and output so people can craft better. –  vfbsilva Aug 16 '13 at 21:01
    
@vfbsilva: Done. –  Dan Aug 16 '13 at 21:11
    
Ok I still confuse about waht you want so I did a draft solution, basically I think you will use a mix of awk and sort. sort -g sorts by absolute numeric value, I assume if yo uuse awk to get the subfield of your interest you can use sort -g to get the desired order. –  vfbsilva Aug 16 '13 at 21:46
add comment

1 Answer

up vote 3 down vote accepted

GNU sort with the -g(--general-numeric-sort) option should be able to do the trick

sort -k5,5g -t '_'  <<!
beginning_num1_734_num2_1.363e+12_num3_800.pdf
beginning_num1_735_num2_7.453e+13_num3_800.pdf
beginning_num1_1007_num2_9.453e+12_num3_1200.pdf
!
beginning_num1_734_num2_1.363e+12_num3_800.pdf
beginning_num1_1007_num2_9.453e+12_num3_1200.pdf
beginning_num1_735_num2_7.453e+13_num3_800.pdf
share|improve this answer
    
What does the -k5,5g do? –  Dan Aug 16 '13 at 22:48
    
Ah! The -k denote which fields in the string to use, g is general numeric sort, and -t '_' is to use the underscore as a seperator. Brilliant! –  Dan Aug 16 '13 at 22:55
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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