Save maximum file extension for variable

I have files where the extension is a number:

backup.1
backup.2
backup.3

Now I need to check what the maximum number is and store that number in a variable. (In the above case it will be i = 3)

+4
source share
2 answers

The problems are actually pretty simple in bash. Bash provides a parameter extension with the removal of the substring, which makes it easy to get the final number from the file name. It has a form ${var##*.}that simply searches to the left of the line until the last occurrence '.', deleting the entire character to and including the point, for example.

var=backup.1
echo ${var##*.}
1

, , , - , backup.[0-9]*, max, , ,

max=0
for i in backup.[0-9]*; do 
    [ "${i##*.}" -gt $max ] && max="${i##*.}"
done
echo "max: $max"

,

max: 3

, .

+5

highest=$(ls backup* | sort -t"." -k2 -n | tail -n1 | sed -r 's/.*\.(.*)/\1/')

:

backup.1
backup.2
backup.3
backup.4
backup.5
backup.6
backup.7
backup.8
backup.9
backup.10

:

echo "${highest}"
10
+2

Source: https://habr.com/ru/post/1692961/


All Articles