my @lines; open FILE, "<", "foo.txt"; while(Hmm.. that removes the 5 lines after each match .. re-reading OP it seems like it mightbe asking for just delete all the lines after the match ... using similar method:){ push @lines, $_; next unless /\byourWord\b/; for 1 .. 5; } close FILE; open FILE, ">", "foo.txt"; print FILE, @lines; close FILE;
my @lines; open FILE, "<", "foo.txt"; while(Another option is [cpan://Tie::File] and a similar approach to above .. or start looping through the array, and just splice off everything after your word is found.){ push @lines, $_; last if /\byourWord\b/; } close FILE; open FILE, ">", "foo.txt"; print FILE, @lines; close FILE;
This sounds like a good job for [cpan://Tie::File]. (the following is untested.)
use strict;
use warnings;
use Tie::File;
my @array;
tie @array, 'Tie::File', 'filename.txt' or die $!;
foreach ( 0 .. $#array ) {
if( $array[$_] =~ /word/ ) {
$#array = ( $_ < $#array ) ? $_ + 1 : $_;
last;
}
}
untie @array;
I often think of [cpan://Tie::Array] as mostly a novelty; not really something you would think of actually using. But I shouldn't think of it that way; it works, it's fast, and it makes some simple tasks even simpler.
Dave
If the files aren't huge, or the word appears fairly early (a few hundred MB) in the file, then you can do this with a "one-liner" (wrapped for viewing; adjust quoting to your OS needs):
perl -e"BEGIN{$/=qq[the word or phrase]}"
-ne"$n=tell ARGV; close ARGV; truncate $ARGV, $n" path\to\the\file
Here's another one-liner that doesn't use a begin block:
perl -ni.bak -e "print; /word/ && last;" file.txt
When the thought came to me, I was surprised at how simple the solution turned out to be.
Dave
That doesn't quite match the OPs stated requirements in that it will preserve the entire 'line', (which could be the entire file if this was a binary file), containing the keyword rather than truncating immediately after the keyword.
Has the advantage that it does matter how big the file, or how far into the file the truncation point is.
Has the disadvantage that it will consume more disc space rather than reducing it--if that was the original intent.
I think it does match the OP's spec: He said he wanted to truncate the line after the word, ie the next line and beyond. Maybe I'm misreading it, but that's how it sounded to me. And the fact that he is speaking of lines leads me to believe that he is dealing with a file that has line endings.
Dave
You can, but these simpler tasks are easier to do with an editor unless the file is very large:
ed file <<<$'/\Alternately replace ed with ex, the same command will work with it./+,$d\nw'
perlmonks.org content © perlmonks.org and ambrus, Anonymous Monk, BrowserUk, davido, davidrw
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03