This is how my variable name looks like: p123456_19100210720_linux-86-64
I am trying to get 123456
in a variable using variable expansion. I am able to get p123456
using variable expansion and reading everything before first _
.
patchname="p123456_19100210720_linux-86-64"
echo ${patchname%%*_}
This outputs p123456
. Is there a way I can get only 123456
?
CodePudding user response:
It will be much easier using BASH
regex operator:
[[ $patchname =~ [0-9] ]] && echo "${BASH_REMATCH[0]}"
123456
Alternative solution using extglob
:
shopt -s extglob
echo "${patchname// ([^0-9]|_*)/}"
123456
CodePudding user response:
You can remove the letters prior to removing everything after _
if using bash
is the preferred option
$ patchname=$(echo "${patchname//[a-z]}")
$ echo "${patchname//_*/}"
123456
Using sed
will be easier
$ sed 's/[a-z]\(.[^_]*\).*/\1/' <<< "$patchname"
123456