sed – How to extract part of string in Bash using regex

I have been trying to extract part of string in bash. I’m using it on Mac.

Pattern of input string:

  • Some random word follow by a /. This is optional.
  • Keyword (def, foo, and bar) followed by hyphen(-) followed by numbers. This can be 2-6 digit numbers
  • These numbers are followed by hyphens again and few hyphen separated words.

Sample inputs and outputs:

abc/def-1234-random-words // def-1234
bla/foo-12-random-words // foo-12
bar-12345-random-words // bar-12345

So I tried following command to fetch it but for some weird reason, it returns entire string.

extractedValue=`getInputString | sed -e 's/.*((def|bar|foo)-[^-]*).*/1/g'`
// and
extractedValue=`getInputString | sed -e 's/.*((def|bar|foo)-d{2,6}).*/1/g'`

I also tried to make it case-insensitive using I flag but it threw error for me:

: bad flag in substitute command: ‘I’

Following are the references I tried:

Read more here: Source link