简体   繁体   中英

delete particular lines from the file using perl regex

Please help me to delete particular block in a file.

input is like ,

<section_begin> a01 
dfasd
adfa
<section_end>
<section_begin> a02
..
eld
...
1 error reported
...
<section_end>
<section_begin> a03 
qwre
adfa
<section_end>

I want to remove the particular block

<section_begin> a02
..
search_string
...
<section_end>

the below command returns first section also.

perl -ne 'print if /<section_begin>/../eld/' a1exp

You can still use the flip-flop operator , but reverse it and match the start and end of section 2:

perl -ne 'print unless /^<section_begin> a02$/ .. /^<section_end>$/' a1exp

unless means if not , so it will not print whenever the expression matches. The flip-flop itself will return false as long as the LHS (left hand side) returns false, and then return true until the RHS returns true, after which it is reset. Read more on that in the documentation .

This can also be used when checking if a section contains a keyword by caching the section before printing.

perl -ne 'if (/^<section_begin>/ .. /^<section_end>/) { $sec .= $_ }; 
          if (/^<section_end>/) { print $sec if $sec !~ /eld/; $sec = "" }' 

You could try to use something like that:

#!/usr/bin/perl

use strict;
use warnings;

my $bool = 0;
while (my $line = <DATA>) {
  if ($line =~ /section_end/) {
    my $temp_bool = $bool;
    $bool = 0;
    next if $temp_bool;
  }
  $bool = 1 if ($line =~ /section_begin/ && $line =~ /a02/ );
  next if $bool;
  print $line;
}




__DATA__

<section_begin> a01 
dfasd
adfa
<section_end>
<section_begin> a02
..
eld
...
1 error reported
...
<section_end>
<section_begin> a03 
qwre
adfa
<section_end>

I set here a bool variable to control the part which should be skipped. To make sure, that the end part of the skipped block will be skipped as well, i use a temp_bool variable.

The straight forward solution might be the best in this case:

perl -ne '/<section_begin> (.+)/;print if $1 ne "a02"' a1exp

$1 will be updated every time the regex sees a new section and then you just print everything not in the "a02" section.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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