Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I asked this question yesterday with Linux, but I realized I need to get it working in both Linux and OS X. Link to earlier question: Get folder with largest number at the end of the name in Linux.

I have some folders r1, r2, r3, etc. and I want to get the name of the folder with the largest number at the end. How do I get the name?

The ls -v solution looks promising, but I want to exclude all folders that don't follow the pattern r[0-9]*

share|improve this question

Since you restrict the filenames this way, you can use the following:

$ ls | grep '^r[0-9]\+$' | cut -c2- | sort -n | tail -n1 | sed 's|^|r|'
  • List files
  • only use those whose names exactly match r[0-9]+, i.e. r followed by any sequence of digits
  • remove the first character, i.e. the r, leaving only the number
  • Sort those according to numeric value
  • get the last (highest) value
  • prepend an r


$ ls
bar baz foo qux r14 r23 r36 r4 r41 r6 r9 rar raz roo
$ ls | grep '^r[0-9]\+$' | cut -c2- | sort -n | tail -n1 | sed 's|^|r|'
share|improve this answer
Also works with leading zeros. – Daniel Beck Apr 23 '11 at 9:16

You can always install the latest version of GNU coreutils in order to have the --version-sort option. Two steps (it takes one or two minutes):

1) Install Homebrew

An easy way would be to install Homebrew, which is sort of a package manager for OS X and helps you to easily install binaries:

ruby -e "$(curl -fsSL"

To get the latest version of sort, install GNU Coreutils:

brew install coreutils

2) Then use gsort

You will now have a sort version that has more capabilities. It will be available under gsort. Now just run the command from your other question, but with gsort instead.

printf '%s\n' r[0-9]* | gsort --version-sort | tail -n 1


I just tested this on 10.6, works fine:

charon:Desktop user$ mkdir r1 r2 r3
charon:Desktop user$ printf '%s\n' r[0-9]* | gsort --version-sort | tail -n 1
share|improve this answer

Looks the the following should work ls | grep r.*[0-9] | tail -n 1. The only stipulation is that in order for this command to show the file name with the longest number, the 1-9 directories must carry a 0 prefix.

For example if you have r1, r2, r3, r1287364763874 and run that command you will be given r3 as the output. But if the lower directories are labeled as r01, r02, r03, r18646483 the command result will be r18646483.

Hope that helps.

Tested on Mac OS 10.5

share|improve this answer

Your Answer


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.