【问题标题】:Replace a string if it is not followed by another string如果字符串后面没有另一个字符串,则替换它
【发布时间】:2021-03-04 04:26:35
【问题描述】:

我想用stephane 字符串替换fortawesome 字符串(如果后面没有/fontawesome-common-type 字符串)。

sed -e 's,"@fortawesome(/^fontawesome-common-types+),"@stephaneeybert\1,g'
sed: -e expression #1, char 65: invalid reference \1 on `s' command's RHS

示例输入:

"@fortawesome/fontawesome-common-types": "^0.2.32"
"name": "@fortawesome/pro-duotone-svg-icons",

及其预期输出:

"@fortawesome/fontawesome-common-types": "^0.2.32"
"name": "@stephane/pro-duotone-svg-icons",

更新:我选择了使用中间变量的简单替代方法:

EXCLUDE=fontawesome-common-types
BUFFER=EkSkLUdE
cat package/package.json \
  | sed -e "s,\"@$REPO_SOURCE/$EXCLUDE,\"@$BUFFER,g" \
  | sed -e "s,\"@$REPO_SOURCE,\"@$REPO_DEST,g" \
  | sed -e "s,\"@$BUFFER,\"@$REPO_SOURCE/$EXCLUDE,g" \ 
  > package/package.out.json;

【问题讨论】:

  • 您能否添加带有预期输出的示例输入
  • 使用perl, perl -pe 's@fortawesome(?!/fontawesome-common-type)@stephane@g' file (demo)
  • @WiktorStribiżew 抱歉,如果我的问题不够清楚,我可以在您的演示中看到您的用例不是我所面临的,无论如何,干杯。
  • 你的用例是什么?你说“替换fortawesome,如果它后面没有/fontawesome-common-type字符串”。这正是我建议的做法。

标签: json regex sed


【解决方案1】:

sed 不支持负前瞻功能。除了支持前瞻的明显的perl 后备,你可以使用这个awk 作为解决方法

awk -F 'fortawesome' -v OFS='stephane' 'NF > 1 {
   s = ""
   for (i=1; i<NF; ++i)
      s = s $i ($(i+1) ~ /^\/fontawesome-common-type/ ? FS : OFS)
   $0 = s $i
} 1' file
  • 此 awk 使用 fortawesome 作为输入字段分隔符,stephane 作为 OFS
  • 当我们在一行中有fortawesome 时,NF &gt; 1 将是真的
  • 我们遍历由fortawesome 分割的字段并跟踪下一个字段
  • 如果下一个字段以/fontawesome-common-type 开头,那么我们保持相同的FS 否则使用OFS

【讨论】:

    【解决方案2】:

    使用临时值:

    exclude='fortawesome/fontawesome-common-type';
    match='fortawesome';
    repl='stephane';
    tmpvar='EkSkLUdE';
    sed "s@$exclude@$tmpvar@g;s@$match@$repl@g;s@$tmpvar@$exclude@g" file > newfile
    

    exclude的所有情况都替换为tmpvars,然后真正预期的matches替换为repls,然后tmpvars又改回excludes。

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      相关资源
      最近更新 更多