[Chicago-talk] -i, -n and print - removing the top x lines w/ each run

Ted Zlatanov tzz at lifelogs.com
Thu Sep 27 18:09:28 PDT 2007

On Thu, 27 Sep 2007 15:20:32 -0500 Andy_Bach at wiwb.uscourts.gov wrote: 

AB> Got it - perldoc perlrun and the  -i switch showed me:
AB> use warnings;
AB> use strict;
AB> my $oldargv = '';
AB> my $argvout ;
AB> while (<>) {
AB>   if ($ARGV ne $oldargv) {
AB>     my $backup = sprintf("%s_%d", $ARGV, $$);
AB>     rename($ARGV, $backup);
AB>     open($argvout, ">$ARGV");
AB>     $oldargv = $ARGV;
AB>   }
AB>   select($argvout);
AB>   if ( 1 .. /--- End/ ) {
AB>      select(STDOUT);
AB>      next unless /\S/;
AB>   }
AB>   print;  # this prints to original filename
AB> }

I think you can get by with the standard `head' utility to print the first
X lines, and this Perl code will print all but the first 20 lines:

perl -ne 'print if $. > 20' file_to_print

The combination of those two is probably the simplest and fastest

You could also use the `split' utility to split the original file into N
chunks of X lines each, then cat all but the first chunk back into the
original file; the first chunk is that first piece you needed.

In pure Perl, to avoid `head' and get inline editing, you can just say
(untested code)

perl -nie ' BEGIN { open F, "out.txt"; } if ($. <= 20) { print F $_; } else { print }; '

which would rewrite the original file without the first 20 lines and
save them to out.txt.  I haven't tested it, but if you can't figure it
out I'll be glad to help further.  Basically, $. is your friend.


More information about the Chicago-talk mailing list