I've got files where the extension is a number:
backup.1 backup.2 backup.3
I now need to check what the highest number is and save this number into a variable. (In the case above it would be i=3)
The problems is actually fairly simple in bash. Bash provides a parameter expansion with substring removal that makes it easy to obtain the final number from the filename. It has the form ${var##*.}
which simply searches from the left of the string to the last occurrence of '.'
removing all character up to, and including the dot, e.g.
var=backup.1
echo ${var##*.}
1
So all you need to is loop over all files matching backup.[0-9]*
and keep a max
variable holding the highest number seen, e.g.
max=0
for i in backup.[0-9]*; do
[ "${i##*.}" -gt $max ] && max="${i##*.}"
done
echo "max: $max"
Output based on your files,
max: 3
Look things over and let me know if you have further questions.
highest=$(ls backup* | sort -t"." -k2 -n | tail -n1 | sed -r 's/.*\.(.*)/\1/')
My files:
backup.1
backup.2
backup.3
backup.4
backup.5
backup.6
backup.7
backup.8
backup.9
backup.10
Output:
echo "${highest}"
10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With