perl to remove lines from file

前端 未结 4 1158
春和景丽
春和景丽 2021-01-29 12:22

I have file that looks like:

ATOM 2517 O   VAL 160 8.337  12.679  -2.487
ATOM 2518 OXT VAL 160 7.646  12.461  -0.386
TER 
ATOM 2519 N   VAL 161 -14.431  5.789 -2         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-29 12:49

    A simple line-by-line script.

    Usage: perl script.pl -i.bak fileglob

    E.g. perl script.pl -i.bak File*MINvac.pdb

    This will alter the original file, and save a backup of each file with the extension .bak. Note that if TER lines appear too close to the end of the file, it will cause warnings. On the other hand, so will the other solutions presented.

    If you do not wish to save backups (use caution, since changes are irreversible!), use -i instead.

    Code:

    #!/usr/bin/perl
    use v5.10;
    use strict;
    use warnings;
    
    my $prev;
    while (<>) {
        if (/^TER/) {
            print scalar <>;  # print next line
            <> for 1 .. 3;    # skip 3 lines
            $prev = undef;    # remove previous line
        } else {
            print $prev if defined $prev;
            $prev = $_;
        }
        if (eof) {  # New file next iteration?
            print $prev;
            $prev = undef;
        }
    }
    

提交回复
热议问题