微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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的单行文件上测试它.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐