-1

I'm looking for a way to be able to parse the string inside Bash script. Here is the test string:

test="+----------+ | count(4) | +----------+ | 0 | +----------+"

I tried to do it with Sed like this:

echo $(echo $test | sed -r 's/|\s(\d+)\s|/\1/')

This returns me whole test string.

And with raw Bash script:

pattern='|\s(\d+)\s|'
if [[ "$test" =~ $pattern ]]
then
        echo "${BASH_REMATCH[1]}"
fi

This doesn't return anything.

What I'm doing wrong and how to achieve this?

anubhava
  • 761,203
  • 64
  • 569
  • 643
sergeda
  • 2,061
  • 3
  • 20
  • 43
  • 1
    sed doesn't support `\d` use `[[:digit:]]` – anubhava Aug 24 '20 at 11:13
  • 1
    There are at least 4 different issues with OP code and not all of them are covered with [Bash Regular Expression — Can't seem to match any of \s \S \d \D \w \W etc](https://stackoverflow.com/questions/18514135/bash-regular-expression-cant-seem-to-match-any-of-s-s-d-d-w-w-etc). – Wiktor Stribiżew Aug 24 '20 at 11:40

1 Answers1

0

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:]].

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563