python – 删除模式之间的行,如果任何模式不存在则打印所有行

我有下一个文件:

G
H
A
B
C
D
N

让我们删除从A到D的行,我们将获得下一个输出:

G
H
N

使用sed’/ A /,/ D / d非常容易,但如果我的文件没有D,那么输出将为空.我想如果没有第二种模式(D)不删除任何内容并显示完整文件.

第二个问题 – 如何在(N)之后删除模式和下一行之间的行? sed’/ A /,1d,但sed’/ A /,/ D / 1d的种类不起作用.

我使用sed,awk或python / bash脚本没有什么不同.

最佳答案 使用perl的许多选项中的一个选项:一旦看到A就将文本保存在累加器中,如果没有看到D,则在最后打印它们.这样你只需要通过文件一次(尽管你经常使用)大文件的内存!).

use strict; use warnings;
my $accumulator = '';  # Text we're holding while we wait for a "D"
my $printing = 1;      # Are we currently printing lines?

while(<>) {
    if(/A/) {  # stop printing; start accumulating
        $printing = 0;
        $accumulator .= $_;    # $_ is the current line
        next;
    }

    if(/D/) {  # we got a D, so we're back to printing
        $accumulator = '';   # discard the text we now know we're deleting
        $printing = 1;
        next;
    }

    if($printing) {
        print;
    } else {
        $accumulator .= $_;
    }
}

print $accumulator;  # which is empty if we had both A and D

我在你的测试用例上尝试了这个,并在你的测试用例中删除了D.它还可以处理具有多个A / D对的文件.我没有在D出现在A之前的文件上测试它,或者在包含A和D的单行文件上测试它.

点赞