Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

sed

ls

I have a directory with files that look like this:

001_something.php  002_something_else.php
004_xyz.php        005_do_good_to_others.php

I ultimately want to create a new, empty PHP file whose name starts with the next number in the series.

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

The preceding code gives me a string like this:

LIST='001 002 004 005 '

I want to grab that 005, increment by one, and then use that number to generate the new filename. How do I do that in BASH?

like image 622
Jake Avatar asked Oct 19 '09 05:10

Jake


2 Answers

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.

like image 187
bmb Avatar answered Sep 23 '22 17:09

bmb


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}'
like image 21
Idelic Avatar answered Sep 19 '22 17:09

Idelic