iPhone Guy
iPhone Guy

Reputation: 1046

Error using a positive lookbehind in a bash script sed on OSX

I am working on manipulating a string (BRANCH_NAME) and removing the front characters up to the forward slash. This is being used to change commit messages in git.

For example, the branch 'feature/pux-1234' is to be changed to pux-1234. There are different value that may exist, exclusive of each other. In this first attempt, I am checking for two values: feature/ and hotfix/.

Here is the code:

# Remove everything up to the first slash if it exists
if  [[ $BRANCH_NAME == *"/"* ]]; then
  PRETRIM=$(echo $BRANCH_NAME | sed -E 's/(?:(?<=feature\/)|(?<=hotfix\/)).+/' )
else
  PRETRIM = $BRANCH_NAME
fi

The error I am receiving is this:

sed: 1: "s/(?:(?<=feature/)|(?< ...": RE error: repetition-operator operand invalid

Ideas to help resolve?

Upvotes: 0

Views: 335

Answers (1)

anubhava
anubhava

Reputation: 784958

For example, the branch feature/pux-1234 is to be changed to pux-1234

You don't need a lookbehind here and anyway sed doesn't support look arounds.

You can use capture groups in sed to match all options in one group and replace with empty string:

s='feature/pux-1234'
sed -E 's~(feature|hotfix)/~~' <<< "$s"

pux-1234

and

s='hotfix/pux-1234'
sed -E 's~(feature|hotfix)/~~' <<< "$s"

pux-1234

Using extglob, you can can do this in bash itself:

shopt -s extglob
echo "${s/+(feature|hotfix)\/}"

pux-1234

Upvotes: 1

Related Questions