You need to match the whole string with the regex pattern, use -n
option with the p
flag, and use [0-9]
/ [[:digit:]]
to match digits, since POSIX regex does not support \d
shorthand:
sed -rn 's/.*\s([0-9]+)\s.*|/\1/p' <<< "$s"
If your sed
does not support \s
, use [[:space:]]
/ [[:blank:]]
POSIX character class instead.
Here,
n
- suppresses the default line output
.*
- matches any zero or more characters
\s
/ [[:space:]]
- a whitespace
([0-9]+)
- capturing group matching one or more digits
\s
/ [[:space:]]
- a whitespace
.*
- any zero or more characters
\1
- replaces the whole match with the contents of Group 1
p
- prints the result of the substitution.
See online sed
demo.
The Bash code you have contains two issues: the pipe chars are special in the POSIX ERE standard (it is used by default in Bash) and you need to escape them to be matched as literal pipe chars. Also, you need to change \d
with [[:digit:]]
or [0-9]
:
pattern='\|\s([0-9]+)\s\|'
See a Bash online demo. Again, if \s
is not supported, use [[:space:]]
.