Reputation: 1274
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
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
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