0

I have alphanumeric file containing following content

z1.doc
z10.doc
z100.doc
z101.doc
z102.doc
z11.doc
z12.doc
z13.doc
z14.doc
z15.doc
z16.doc
z17.doc
z18.doc
z19.doc
z2.doc
z20.doc
z3.doc
z4.doc
z5.doc
z6.doc
z7.doc
z8.doc
z9.doc

I want to sort it using unix/linux sort command to get the following output

z1.doc
z2.doc
z3.doc
z4.doc
z5.doc
z6.doc
z7.doc
z8.doc
z9.doc
z10.doc
z11.doc
z12.doc
z13.doc
z14.doc
z15.doc
z16.doc
z17.doc
z18.doc
z19.doc
z20.doc
z100.doc
z101.doc
z102.doc

I have used following commandline

sort -t "." -n -k1 sortAlphanumeric.txt

But output is not as required. Is it possible using sort command to sort this to get the required output or i should choose some other scripting language.

2

4 Answers 4

1

Tell sort that your key starts on position 2 and you want to sort numerically:

sort -k1.2n
Sign up to request clarification or add additional context in comments.

Comments

1

You can always perform sort with argument -V to sort alphanumeric string..

$ sort -V inputfile > outputfile

$ cat inputfile  
z1.doc  
z10.doc  
z100.doc  
z101.doc  
z102.doc  
z11.doc  
z12.doc  
z13.doc  
z14.doc  
z15.doc  
z16.doc  
z17.doc  
z18.doc  
z19.doc  
z2.doc  
z20.doc  
z3.doc  
z4.doc  
z5.doc  
z6.doc  
z7.doc  
z8.doc  
z9.doc    

$ cat outputfile
z1.doc  
z2.doc  
z3.doc  
z4.doc  
z5.doc  
z6.doc  
z7.doc  
z8.doc  
z9.doc  
z10.doc  
z11.doc  
z12.doc  
z13.doc  
z14.doc  
z15.doc  
z16.doc  
z17.doc  
z18.doc  
z19.doc  
z20.doc  
z100.doc  
z101.doc  
z102.doc

Comments

0

cheat a little bit. say that the field delimiter is 'z' and sort numerically using second field.

sort -t z -k 2 -n < fff
z1.doc
z2.doc
z3.doc
z4.doc
z5.doc
z6.doc
z7.doc
z8.doc
z9.doc
z10.doc
z11.doc
z12.doc
z13.doc
z14.doc
z15.doc
z16.doc
z17.doc
z18.doc
z19.doc
z20.doc
z100.doc
z101.doc
z102.doc

Comments

0

If you don't want to figure out where the number/letter boundaries are in advance for your data, you can use the module Sort::Key::Natural and natsort

perl -MSort::Key::Natural -e "print natsort <>" sortAlphanumeric.txt

1 Comment

Converted solution to Sort::Key::Natural from Sort::Naturally because of the latter ignores non-word characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.