Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save highest file extension to a variable

Tags:

bash

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)

like image 404
Lukashoi Avatar asked Mar 07 '23 00:03

Lukashoi


2 Answers

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.

like image 142
David C. Rankin Avatar answered Mar 20 '23 03:03

David C. Rankin


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
like image 22
Viktor Khilin Avatar answered Mar 20 '23 03:03

Viktor Khilin