Find highest numbered filename in a directory where names start with digits

Using only standard tools, the following will give you the prefix for the new file (006):

ls [0-9]* | sed 's/_/ _/' | sort -rn | awk '{printf "%03d", $1 + 1; exit}'

$ LIST=($LIST)
$ newfile=`printf %03d-whatever $((10#${LIST[${#LIST}]}+1))`
$ echo $newfile
006-whatever

So, that's bash-specific. Below is a any-posix-shell-including-bash solution, tho I imagine something simpler is possible.

$ cat /tmp/z
f () {
    eval echo \${$#} | sed -e 's/^0*//'
}
LIST='001 002 004 005 '
newname=`printf %03d-whatever $(($(f $LIST) + 1))`
echo $newname
$ sh /tmp/z
006-whatever
$ 

Do you need the whole LIST?

If not

LAST=`exec ls $MY_DIR | sed 's/\([0-9]\+\).*/\1/g' | sort -n | tail -1`

will give you just the 005 part and

printf "%03d" `expr 1 + $LAST`

will print the next number in the sequence.

Tags:

Shell

Bash

Sed

Ls