简体   繁体   English

在 OSX 上的 bash 脚本 sed 中使用正向后视时出错

[英]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.我正在处理一个字符串 (BRANCH_NAME) 并删除前面的字符直到正斜杠。 This is being used to change commit messages in git.这用于更改 git 中的提交消息。

For example, the branch 'feature/pux-1234' is to be changed to pux-1234.例如,分支 'feature/pux-1234' 将更改为 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/.在第一次尝试中,我检查了两个值:feature/ 和 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 sed: 1: "s/(?:(?<=feature/)|(?<...": RE 错误:重复运算符操作数无效

Ideas to help resolve?有助于解决的想法?

For example, the branch feature/pux-1234 is to be changed to pux-1234例如分支feature/pux-1234要改成pux-1234

You don't need a lookbehind here and anyway sed doesn't support look arounds.您不需要在这里进行环视,无论如何sed不支持环视。

You can use capture groups in sed to match all options in one group and replace with empty string:您可以使用sed中的捕获组来匹配一组中的所有选项并替换为空字符串:

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:使用extglob ,您可以在bash本身中执行此操作:

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

pux-1234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM