替换两个字符串之间的指定字符?

kem*_*aro 2 sed replace

我有事要完成。我需要将所有出现的 & 替换<ex> </ex>为 #内部或之间。下面的实际例子:

a & b & c <ex> a & b & c </ex> a & b & c
Run Code Online (Sandbox Code Playgroud)

再次,我需要替换所有出现的 & 内部<ex>和之前</ex>

预期输出:

a & b & c <ex> a # b # c </ex> a & b & c
Run Code Online (Sandbox Code Playgroud)

请发布关于你们如何设法做到的解释。

编辑#1

请只为我提供sed解决方案,因为我将在 AS400 系统上运行它并且无法安装 Perl 或任何其他解释器。

Sté*_*las 7

如果<ex>...</ex>每行只出现一次:

sed -e :1 -e 's@\(<ex>.*\)&\(.*</ex>\)@\1#\2@;t1'
Run Code Online (Sandbox Code Playgroud)

如果可能有多个事件并且它们不嵌套(或者它们嵌套并且您想替换&最深的事件中唯一的):

sed '
  s|_|_u|g        # replace all underscores with "_u"
  s|(|_o|g        # replace all open parentheses with "_o"
  s|)|_c|g        # replace all close parentheses with "_c"
  s|<ex>|(|g      # replace all open ex tags with "("
  s|</ex>|)|g     # replace all close ex tags with ")"

  :1              # a label

  s/\(([^()]*\)&\([^()]*)\)/\1#\2/g
                  # find:
                  #   an open parentheses, 
                  #   some non-parentheses chars (captured),
                  #   an ampersand, 
                  #   some non-parentheses chars (captured) and 
                  #   a close parentheses, 
                  # replace with
                  #   the first captured text, 
                  #   an octothorpe
                  #   the second captured text, 
                  # globally in the current record.

  t1              # if there was a successful replacement, goto label "1",
                  # else carry on

  s|(|<ex>|g      # restore open tags
  s|)|</ex>|g     # restore close tags
  s|_o|(|g        # restore open parentheses
  s|_c|)|g        # restore close parentheses
  s|_u|_|g        # restore underscores
'
Run Code Online (Sandbox Code Playgroud)

如果它们可能嵌套并且您想替换封闭的:

sed '
  s|_|_u|g;s|(|_o|g;s|)|_c|g
  s|<ex>|(|g;s|</ex>|)|g;:1
  s/\(([^()]*\)(\([^()]*\))\([^()]*)\)/\1_O\2_C\3/g;t1
  :2
  s/\(([^()]*\)&\([^()]*)\)/\1#\2/g;t2
  s|(|<ex>|g;s|)|</ex>|g
  s|_O|<ex>|g;s|_C|</ex>|g
  s|_o|(|g;s|_c|)|g;s|_u|_|g'
Run Code Online (Sandbox Code Playgroud)