Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: how to check for a word in a file and if found remove previous and next -- 3 oneliner variations

by Discipulus (Abbot)
on Jan 26, 2016 at 11:50 UTC ( #1153667=note: print w/replies, xml ) Need Help??


in reply to how to check for a word in a file and if found remove that line, the above line and the below line from the file.

Yes, i got fixed with this and i made unsuccesfull tries using eof..eof flip-flop to process even files..
anyway now i get two semi-obfuscated oneliners, the first, simpler, is called with a single arg (the name of file):
# $y is <C>yet</C> set for the second read, @u is <C>unwanted</C> <P> perl -lnE "BEGIN{push @ARGV,$ARGV[0]}eof&&!$y?$y=close ARGV:/XXXXX/&&! +$y?push @u,$.-1..$.+1:$y&&!($.~~@u)?say:0" next-and-previous.txt 11111 22222 33333 44444<P>
while the latter is parametrizable one: firts arg is the regex used to match unwanted strings, the second is the number of lines to be removed after and before and then the filename:
perl -lnE "BEGIN{$r=shift;$r=qr/$r/;$n=shift@ARGV;push @ARGV,$ARGV[0]} +eof&&!$y?$y=close ARGV:/$r/&&!$y?push @u,$.-$n..$.+$n:$y&&!($.~~@u)?s +ay:0" XXXXX 1 next-and-previous.txt 11111 22222 33333 44444 perl -lnE "BEGIN{$r=shift;$r=qr/$r/;$n=shift;push @ARGV,$ARGV[0]}eof&& +!$y?$y=close ARGV:/$r/&&!$y?push @u,$.-$n..$.+$n:$y&&!($.~~@u)?say:0" + XXXXX 2 next-and-previous.txt 22222

I promise i'll try to no bother you anymore with this.. :=)

update the parametrized oneliner can be shortend using -s switch (that has some problem anyhow) It is the second time i use -- too.

perl -slnE "BEGIN{$r=qr/$r/;push @ARGV,$ARGV[0]}eof&&!$y?$y=close ARGV +:/$r&&!$y?push@u,$.-$n..$.+$n:$y&&!($.~~@u)?say:0" -- -r=XXXXX -n=1 next-and-previous.txt 11111 22222 33333 44444

L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
  • Comment on Re: how to check for a word in a file and if found remove previous and next -- 3 oneliner variations
  • Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1153667]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2019-10-16 04:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?