Ubuntu – Determine the next name for a particular file

bash

I have to create a script which takes my <username> _Release $META $PROJECT

here META=red, PROJECT=green

Next I need determine the next release name for that META and PROJECT for your user

eg: /user/desktop/release/red/green/file_2
next should be /user/desktop/release/red/green/file_3

So imagine there are many files in that folder so I need to determine which is the highest one is and increment it. I am thinking should I have search all the folders first I am really confused.

Best Answer

My solution is to look into that directory for the files and then pick the last one:

filename=`find . | sort -t_ -k2 -n | tail -1`

then show the new file's name:

echo ${filename%_*}_$(( ${filename##*_} + 1 ))

let's test it:

$ mkdir test
$ cd test
$ touch file_{1..999}
$ filename=`find . | sort | tail -1`
$ echo $filename
./file_999

Get the file name:

$ echo ${filename%_*}
./file

Get the number +1:

$ echo $(( ${filename##*_} + 1 ))
1000

Merge them:

$ echo ${filename%_*}_$(( ${filename##*_} + 1 ))
./file_1000