Search code examples
bashzshparameter-expansion

How to keep/remove numbers in a variable in shell?


I have a variable such as:

disk=/dev/sda1

I want to extract:

  • only the non numeric part (i.e. /dev/sda)
  • only the numeric part (i.e. 1)

I'm gonna use it in a script where I need the disk and the partition number. How can I do that in shell (bash and zsh mostly)?

I was thinking about using Shell parameters expansions, but couldn't find working patterns in the documentation.

Basically, I tried:

echo ${disk##[:alpha:]}

and

echo ${disk##[:digit:]}

But none worked. Both returned /dev/sda1


Solution

  • With bash and zsh and Parameter Expansion:

    disk="/dev/sda12"
    echo "${disk//[0-9]/} ${disk//[^0-9]/}"
    

    Output:

    /dev/sda 12