jett
jett

Reputation: 1274

How can I add directory with ascending name such as dir-000, dir-001 etc

I want to copy a directory into another directory at various times. Each time, I want the new name to be one number higher than before / I want to be able to grab that number and store it into a variable.

So if I have a:

mymaindir

/home/user/dirs/STRING_000
/home/user/dirs/STRING_001

And I run my script, mymaindir would be copied to /home/user/dirs/STRING_002 and I could get the value 2 from that. I've just been looking at different things like split but it doesn't seem to be what I'm looking for.

Upvotes: 2

Views: 57

Answers (2)

anubhava
anubhava

Reputation: 785216

awk one liner can do that:

arr=( $(find . -name "STRING_*" | awk -F "_" '{if ($2>max) max=$2} 
        END{max++; printf("%d STRING_%03d\n", max, max)}') )

maxVal=${arr[0]}
fileName=${arr[1]}

Upvotes: 2

perreal
perreal

Reputation: 97948

You can use some form of this:

highest=$(find -name 'string_[0-9]*' | cut -d_ -f2 | sort -nr | head -1)
newname="string_$(printf "%03d" "$(( $highest+ 1))")"

Upvotes: 1

Related Questions