regexbashbuildkite

Get the number between two special characters in bash


I have a string that is actually a buildkite commit message and I am trying to retrieve a number (pull request number) between two special characters.

E.g. the string could be something like

"some commit message (#36)

* test

* unsquashed

* etc

* bla"

Using bash, now I want to get the number 36 from the above string. Unfortunately I will not be able to use sed or grep with perl-regexp.

Help is very much appreciated.


Solution

  • Use the parameter expansion operators.

    commit_msg="some commit message (#36)
    * test
    * unsquashed
    * etc
    * bla"
    id=${commit_msg#*(#} # remove everything up to (#
    id=${id%%)*} # remove everything starting from )
    echo "$id"