1

I have a directory containing three files, for example, 5.war, 6.war and 7.war.

What command will return the file with the "smallest" filename from this directory? (In this case, 5.war.)

1
  • 3
    This is not clear at all. Are all files numeric and you want the smallest numeric value, or sorted alphabetically (which means 22 goes before 3)? What about names with letters, e.g. a.war?
    – Sven
    Jan 21, 2015 at 21:15

2 Answers 2

3

ls sorts by name by default. If there's no directories to contend with, then just do this:

ls | head -1

To add some completion, if you have to worry about directories, do the following:

ls -p | egrep -v /$ | head -1
3
  • I must mention: it will think 10.war is "smaller" as 2.war.
    – peterh
    Jan 22, 2015 at 9:19
  • 1
    The original title said "alphabetically smallest". The original user hasn't clarified.
    – Hyppy
    Jan 23, 2015 at 18:07
  • Ok, understood!
    – peterh
    Jan 23, 2015 at 18:09
1

Unfortunately, ls sorts the file names alphabetically, which isn't correct for numbers. For example, 10.war will before 2.war, which is not what you wish.

Probably you can find some, more intelligent sorting tool by google, but in the absence of that I would suggest:

  1. If your files are alphabetical, @Hyppy 's solution is perfect for you.
  2. If they are numerical, instead of head -1, I suggest a numerical sort: ls|sort -n|head -1
  3. If there are both, you had to find some alternative (in your place I googled for a more intelligent sorting tool).
1
  • 1
    Upvoted as a good alternative if someone is looking for another sorting method. sort is badass.
    – Hyppy
    Jan 23, 2015 at 18:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .