在之前和之后查找替换字符串

时间:2016-12-25 19:24:18

标签: sed

我一直在努力做一个sed替换。出于某种原因,我只能围绕sed和正则表达式(这是我的第二个sed问题)

基本上我想查找文本并替换然后找到下一个出现的某些文本并替换

到目前为止,我有这个

echo "This could be anywhere and this bit should be changed \$\{hcvar-BookName\} and this would remain" | sed 's/$\\{hcvar-/" + hcvar-/g'

返回:

*This could be anywhere and this bit should be changed " + hcvar-BookName\} and this would remain*

但是我想要回归

*This could be anywhere and this bit should be changed " + hcvar-BookName + " and this would remain*

这将用+"

替换}

逻辑如下:

Find: \$\{hcvar-
Replace with:  " + hcvar-
Then find the next occurrence of: \}
Replace with: + "

要替换的第二个位将在包含以下内容的字符串后面:hcvar-

这适用于以下字符串示例

  • 这可能是任何地方,应该改变这一点 \ $ {hcvar-BookName},这将保持
  • 这可能是任何地方 这个位应该改为\ $ {hcvar-somethingelse},这样就可以了 保持
  • 这可能是任何地方,应该改变这一点 \ $ {hcvar-wouldnevercontainspaces}这将保持

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

假设您的输入实际上是:

... changed ${hcvar-BookName} and ...

然后以下内容将起作用:

$ sed 's/${\([^}]*\)}/" + \1 + "/' file.txt
This could be anywhere and this bit should be changed " + hcvar-BookName + " and this would remain

注意使用单引号来保留shell的特殊字符:

$ echo '...changed ${hcvar-BookName} and ...' | sed '...' 

如果输入确实使用\{,即:... $\{hello\} ...,那么这可能有效:

$ sed 's/$\\{\([^}]*\)\\}/" + \1 + "/' file.txt
This could be anywhere and this bit should be changed " + hcvar-BookName + " and this would remain

故障:

s/            /          / # Replace ... with ...
  ${         }             # Literal ${ and literal }
    \(     \)              # \( and \) is a capturing group
      [^}]*                # Match everything but } zero or more times
               " + \1 + "  # \1 will be expanded to the captured result
                           # from \(, \). The rest is literal

如果您需要在每一行上进行多次替换,请添加g个小文:

s/pattern/replacement/g
#                     ^ Global flag

答案 1 :(得分:0)

你需要用反斜杠逃避$:

echo "This could be anywhere and this bit should be changed \$\{hcvar-BookName\} and this would remain" | sed -e 's/\$\\{hcvar-/" + hcvar-/g' -e 's/\\}/ +/'

输出:

This could be anywhere and this bit should be changed " + hcvar-BookName + and this would remain