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.)

HopelessN00b
  • 53,385
  • 32
  • 133
  • 208
Jerome Ansia
  • 261
  • 1
  • 2
  • 9
  • 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 '15 at 21:15

2 Answers2

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
Hyppy
  • 15,458
  • 1
  • 37
  • 59
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).
peterh
  • 4,914
  • 13
  • 29
  • 44
  • 1
    Upvoted as a good alternative if someone is looking for another sorting method. `sort` is badass. – Hyppy Jan 23 '15 at 18:20