【问题标题】:sed replace second last line of filesed 替换文件的倒数第二行
【发布时间】:2013-06-03 15:58:16
【问题描述】:

我想替换文件的倒数第二行,我知道 $ 用于最后一行,但不知道如何从末尾说第二行。

parallel (
{
ignore(FAILURE) {
build( "Build2Test", BUILDFILE: "", WARFILE: "http://maven.example.com/130602.0.war", STUDY: "UK", BUG: "33323" )
}},
)

我想用}} 替换}}, 简而言之我想删除, 逗号,但是这个文件有很多其他代码所以我不能使用模式匹配我需要使用文件末尾的第二行。

【问题讨论】:

    标签: regex linux sed


    【解决方案1】:

    以下应该可以工作(请注意,在某些系统上,您可能需要删除所有 cmets):

    sed '1 {        # if this is the first line
      h               # copy to hold space
      d               # delete pattern space and return to start
    }
    /^}},$/ {       # if this line matches regex /^}},$/
      x               # exchange pattern and hold space
      b               # print pattern space and return to start
    }
    H               # append line to hold space
    $ {             # if this is the last line
      x               # exchange pattern and hold space
      s/^}},/}}/      # replace "}}," at start of pattern space with "}}"
      b               # print pattern space and return to start
    }
    d               # delete pattern space and return to start' 
    

    或者精简版:

    sed '1{h;d};/^}},$/{x;b};H;${x;s/^}},/}}/;b};d'
    

    例子:

    $ echo 'parallel (
    {
    ignore(FAILURE) {
    build( "Build2Test", BUILDFILE: "", WARFILE: "http://maven.example.com/130602.0.war", STUDY: "UK", BUG: "33323" )
    }},
    )' | sed '1{h;d};/^}},$/{x;b};H;${x;s/^}},/}}/;b};d'
    parallel (
    {
    ignore(FAILURE) {
    build( "Build2Test", BUILDFILE: "", WARFILE: "http://maven.example.com/130602.0.war", STUDY: "UK", BUG: "33323" )
    }}
    )
    

    【讨论】:

      【解决方案2】:

      如果您知道如何更改第 N 行,只需先反转文件,例如它不像其他 sed 解决方案那样专业,但可以工作...... :)

      tail -r <file | sed '2s/}},/}}/' | tail -r >newfile
      

      例如从下一个输入

      }},
      }},
      }},
      }},
      }},
      

      以上使

      }},
      }},
      }},
      }}
      }},
      

      tail -r 是 BSD 等效于 Linux 的 tac 命令。在 Linux 上使用 tac 在 OS X 或 Freebsd 上使用 tail -r。 Bot 做同样的事情:以相反的行顺序打印文件(最后一行打印为第一行)。

      【讨论】:

        【解决方案3】:

        反转文件,处理第 2 行,然后重新反转文件:

        tac file | sed '2 s/,$//' | tac
        

        要将结果保存回“文件”,请将其添加到命令中

         > file.new && mv file file.bak && mv file.new file
        

        或者,使用ed 脚本

        ed file <<END
        $-1 s/,$//
        w
        q
        END
        

        【讨论】:

          【解决方案4】:

          这可能对你有用(GNU sed):

          sed '$!N;$s/}},/}}/;P;D' file
          

          在模式空间中保留两行,并在文件末尾替换所需的模式。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-06-27
            • 1970-01-01
            • 2017-12-20
            • 1970-01-01
            相关资源
            最近更新 更多