简体   繁体   English

用 sed 和 perl 中的多行文本替换多行文本

[英]replace multi line text with multiline text in sed and perl

Here is my file这是我的文件

      start
      exit 0

      status
      exit 0

      stop
      exit 0

the result file should be结果文件应该是

      start
      exit 0

      status
      exit 152

      stop
      exit 0

any help is appreciated How can I do it using sed and perl任何帮助表示赞赏我如何使用 sed 和 perl 做到这一点

Using Awk使用Awk

Input输入

$ cat f
      start
      exit 0

      status
      exit 0

      stop
      exit 0

Output输出

$ awk '/exit/ && p {sub($NF,"152")}{p=/status/}1'  f
      start
      exit 0

      status
      exit 152

      stop
      exit 0

Explanation解释

  • p=/status/ Set variable p true whenever awk finds word status p=/status/每当awk找到单词状态时,将变量p设置为真
  • /exit/ && p when awk finds word exit on current record and variable p evaluates true then /exit/ && pawk在当前记录上找到单词exit并且变量p评估为真时

sub(regexp, replacement [, target])子(正则表达式,替换 [,目标])

Search target, which is treated as a string, for the leftmost, longest substring matched by the regular expression regexp.搜索目标,将其视为字符串,查找正则表达式 regexp 匹配的最左边最长的子字符串。 Modify the entire string by replacing the matched text with replacement.通过用替换替换匹配的文本来修改整个字符串。 The modified string becomes the new value of target.修改后的字符串成为目标的新值。 Return the number of substitutions made (zero or one).返回替换的次数(零或一)。 If 3rd argument is omitted, then the default is to use and alter $0 .如果省略第三个参数,则默认为使用和更改$0

  • sub($NF,"152")

Substitute last field ( $NF ) with 152 of current record, since 3rd argument is not given hence, default $0 is altered.用当前记录的152替换最后一个字段 ( $NF ),因为没有给出第三个参数,因此默认$0被更改。

  • } 1

1 always evaluates to true, it performs default operation {print $0} 1总是评估为真,它执行默认操作{print $0}

perl -pe's/exit \K\d+/152/ if $f; $f = /status/'

Usage:用法:

perl -i~ -pe'...' file            # Edit in place with backup
perl -i -pe'...' file             # Edit in place without backup
perl -pe'...' file.in >file.out   # Read from file
perl -pe'...' <file.in >file.out  # Read from stdin

With sed one can use:使用 sed 可以使用:

$ sed '/status/{n;s/0/152/}' input
      start
      exit 0

      status
      exit 152

      stop
      exit 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM