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.

This is the data what I want to sort. But sort treats the numeric to string, the data it no sorted as I expected.

/home/files/profile1
/home/files/profile10
/home/files/profile11
/home/files/profile12
/home/files/profile14
/home/files/profile15
/home/files/profile16
/home/files/profile2
/home/files/profile3
/home/files/profile4
/home/files/profile5
/home/files/profile6
/home/files/profile7
/home/files/profile8
/home/files/profile9

I want to sort this to,

/home/files/profile1
/home/files/profile2
/home/files/profile3
/home/files/profile4
/home/files/profile5
/home/files/profile6
/home/files/profile7
/home/files/profile8
/home/files/profile9
/home/files/profile10
/home/files/profile11
/home/files/profile12
/home/files/profile14
/home/files/profile15
/home/files/profile16

Is there a good way by bash script? I can't use ruby or python script in here.

share|improve this question
    
try using "sort -nd" –  bobah Jun 26 '12 at 10:29
    
@bobah, "sort: options `-dn' are incompatible" –  maxschlepzig Jun 26 '12 at 10:41
6  
sort -V would do. –  Thor Jun 26 '12 at 11:08
2  
@Thor. your comment would make a good answer –  Peter.O Jun 26 '12 at 11:35
add comment

3 Answers

up vote 10 down vote accepted

You can use a temporary sentinel character to delimit the number:

$ sed 's/\([0-9]\+\)/;\1/' log | sort -n -t\; -k2,2 | tr -d ';'

Here, the sentinel character is ';' - it must not be part of any filename you want to sort - but you can exchange the ';' with any character you like. You have to change the sed, sort and tr part then accordingly.

The pipe works as follows: The sed command inserts the sentinel before any number, the sort command interprets the sentinel as field delimiter, sorts with the second field as numeric sort key and the tr commands removes the sentinel again.

log denotes the input file - you can also pipe your input into sed.

share|improve this answer
    
I like the way you resolved the problem :) –  SHW Jun 26 '12 at 11:29
add comment

If all your file names have the same prefix before the final numeric part, ignore it when sorting:

sort -k 1.20n

(20 is the position of the first digit. It's one plus the length of /home/files/profile.)

If you have several different non-numeric parts, insert a sentinel.

share|improve this answer
add comment

This is very similar to this question. The trouble is that you have an alphanumeric field that you are sorting on, and -n doesn't treat that sensibly, however version sort (-V) does. Thus use

sort -V
share|improve this answer
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.