cancel
Showing results for 
Search instead for 
Did you mean: 

Perl Help

SOLVED
Go to solution
Shaf_1
Advisor

Perl Help

Hello,

I am trying to delete the first 15 lines from each text file I have. Is there a easy perl script for this?

The attached file is similar to the text file I am working with. It is always going to be the first 15 lines.
9 REPLIES
Ermin Borovac
Honored Contributor

Re: Perl Help

You can try the following

perl -ni.orig -e 'print if $. > 15' ...

It should delete first 15 lines in and leave original in .orig.
Shaf_1
Advisor

Re: Perl Help

Hello Ermin,

I tried this since I am trying to run it for over 1000 files at once. But what is happening is that it only update the first file.

perl -i -n -e 'print if$. > 15;' *.txt

What could I be doing wrong?
Ermin Borovac
Honored Contributor
Solution

Re: Perl Help

Just do it in a loop instead

for file in *.txt
do
perl -ni.orig -e 'print if $. > 15' $file
done
Alexander Chuzhoy
Honored Contributor

Re: Perl Help

Here's the desired perl script:
foreach $file (glob "*.txt") {
@ARGV=$file;
$^I=".bak";#creates backup with .bak extension
while (<>) {
if ($.>15) {
print;
}
}
}


By the way for any perl question refer to:
www.perlmonks.org
Best and quick answers.
Vitaly Karasik_1
Honored Contributor

Re: Perl Help

Shaf_1
Advisor

Re: Perl Help

This one liner works for one file at a time.

# delete first 10 lines
   perl -i.old -ne 'print unless 1 .. 10' foo.txt

Is there a easy way to run it for a bunch of files at once?

Does it matter what shell I am
Hein van den Heuvel
Honored Contributor

Re: Perl Help

Just replace your filespec with a wild-carded on like *.txt

See for example:

http://www.rice.edu/web/perl-edit.html


The only tricky part with that iss to recognize file transitions, where you'll need to reset the line number for the work you want to do.

So a solution might be:

perl -ni.old -e 'print unless ($.<10); close ARGV if eof' *.txt


Hein.
NiCK_76
Respected Contributor

Re: Perl Help

sed '1,15d' textfile
just for fun
Shaf_1
Advisor

Re: Perl Help

Thanks for all the help.