如何用空行替换两个模式之间的代码块?

问题描述 投票:-1回答:4

我正在尝试用空行替换两个模式之间的代码块使用下面的命令尝试

sed '/PATTERN-1/,/PATTERN-2/d' input.pl

但它只删除了模式之间的界限

PATTERN-1:“= head”PATTERN-2:“= cut”

input.pl包含以下文本

=head
hello
hello world
world
morning
gud
=cut

所需输出:

=head





=cut

谁可以帮我这个事?

perl awk sed
4个回答
1
投票
$ awk '/=cut/{f=0} {print (f ? "" : $0)} /=head/{f=1}' file
=head





=cut

1
投票

要修改给定的sed命令,请尝试

$ sed '/=head/,/=cut/{//! s/.*//}' ip.txt
=head





=cut
  • //!匹配开始/结束范围以外的其他范围,可能取决于sed实现它是否动态匹配范围或静态只匹配其中一个。适用于GNU sed s/.*//清除这些线条

0
投票
awk '/=cut/{found=0}found{print "";next}/=head/{found=1}1' infile

# OR
# ^ to take care of line starts with regexp
awk '/^=cut/{found=0}found{print "";next}/^=head/{found=1}1' infile

说明:

awk '/=cut/{                    # if line contains regexp 
        found=0                 # set variable found = 0
     }
     found{                     # if variable found is nonzero value
       print "";                # print ""
       next                     # go to next line
     }
     /=head/{                   # if line contains regexp
       found=1                  # set variable found = 1
     }1                         # 1 at the end does default operation
                                # print current line/row/record
   ' infile

检测结果:

$ cat infile
=head
hello
hello world
world
morning
gud
=cut

$ awk '/=cut/{found=0}found{print "";next}/=head/{found=1}1' infile
=head





=cut

0
投票

这可能适合你(GNU sed):

sed '/=head/,/=cut/{//!z}' file

消除=head=cut之间的界限。

© www.soinside.com 2019 - 2024. All rights reserved.