【问题标题】:need to convert individual sed commands into one single sed script需要将单个 sed 命令转换为一个 sed 脚本
【发布时间】:2012-06-29 08:31:36
【问题描述】:

我的文件内容如下,所需的输出如下所示。使用单独的 sed 命令,我可以修改文件内容。说

sed -i -e 's!<tag1>FIELD1</tag1>!<tag1>Replaced contents of field1</tag1>! filename

但是我很难尝试用单个 sed 脚本文件替换这些单独的命令。

This is a sample file containing a few tags

<tag1>FIELD1</tag1>
<tag2>FIELD2</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

想要的输出是

This is a sample file containing a few tags

<tag1>Replaced contents of field1</tag1>
<tag2>Replaced contents of field2</tag2>
<tag2>Some addition to field2</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

<tag1>FIELD1 Do not change me</tag1>
<tag2>FIELD2 Do not change me</tag2>

【问题讨论】:

    标签: sed


    【解决方案1】:

    您可以链接-e 表达式。

    例如:

    sed -e 's!<tag1>FIELD1</tag1>!<tag1>Replaced contents of field1</tag1>!g' -e 's!<tag2>FIELD2</tag2>!<tag2>Replaced contents of field2</tag2>\n<tag2>Some addition to field2</tag2>!g' filename
    

    【讨论】:

      【解决方案2】:
      tag=(  "tag1"          "tag2" )
      find=( "FIELD1"        "FIELD2" )
      repl=( "Replacement 1" "Replacement 2" )
      regex=
      I=$'\x01' # sed delimiter
      for (( i=0; i<${#find[@]}; i++ )) ;do
          regex+="s$I<${tag[i]}>${find[i]}</${tag[i]}>$I<${tag[i]}>${repl[i]}</${tag[i]}>${I}g;"
      done
      sed "$regex" "$file"
      

      您可能想要也可能不想要或不需要每个表达式末尾的g

      【讨论】:

        【解决方案3】:

        这对我有用。

        sed_script 文件(单个文件)

        /&lt;tag1&gt;FIELD1&lt;\/tag1&gt;/s!&lt;tag1&gt;FIELD1&lt;/tag1&gt;!&lt;tag1&gt;Replaced contents of field1&lt;/tag1&gt;!
        /&lt;tag2&gt;FIELD2&lt;\/tag2&gt;/c\
        &lt;tag2\&gt;Replaced contents of field2&lt;/tag2&gt;\
        &lt;tag2\&gt;Some addition to field2&lt;/tag2&gt;

        【讨论】:

          猜你喜欢
          • 2016-08-26
          • 2018-11-09
          • 1970-01-01
          • 2010-10-23
          • 1970-01-01
          • 1970-01-01
          • 2021-07-25
          • 2014-05-21
          • 1970-01-01
          相关资源
          最近更新 更多