How to delete or get the number in the tail from a string in shell script?

Posted on

How to delete or get the number in the tail from a string in shell script (bash script)? Okay to call other tools.

For example, from “/dev/sda8”, I want to get “/dev/sda” and “8” separately.

This can be achieved by using sed as follows.

To get the string after deleting the tailing numbers, we can use sed to replace the tailing numbers with an empty string.

str=sda8

# get the string with the number tail
strhead=$(echo "sda8" | sed 's/[0-9]*$//')

To get the tailing numbers by making use of the strhead we got, by getting the substring from the original string from the position after the strhead.

strtail=${str:${#strhead}}

After these operations, we can get the split strings.

$ echo $strhead
sda

$ echo $strtail
8