Search code examples
bashparametersparameter-expansion

Remove leading digits from a string with Bash using parameter expansion


The initial string is RU="903B/100ms" from which I wish to obtain B/100ms.

Currently, I have written:

#!/bin/bash
RU="903B/100ms"
RU=${RU#*[^0-9]}
echo $RU 

which returns /100ms since the parameter expansion removes up to and including the first non-numeric character. I would like to keep the first non-numeric character in this case. How would I do this by amending the above text?


Solution

  • You can use BASH_REMATCH to extract the desired matching value:

    $ RU="903B/100ms"
    $ [[ $RU =~ ^([[:digit:]]+)(.*) ]] && echo ${BASH_REMATCH[2]}
    B/100ms
    

    Or just catch the desired part as:

    $ [[ $RU =~ ^[[:digit:]]+(.*) ]] && echo ${BASH_REMATCH[1]}
    B/100ms