Perl one liner to add text at last but one line of a large file

Viewed 235

I am novice to Perl. Please help me in the programming using either one liner or a Perl proc or a Perl program. Let's suppose my input file is input.txt and its contents are as follows :

This is an example 

This file has three lines

Oh you are mistaken. It has many lines 

I want my text here 

Thanks for making it to the last line of input.txt. 

Below is the output file that I want to generate:

This is an example 

This file has three lines

Oh you are mistaken. It has many lines 

I want my text here

This line has special characters like $

I love this community 

Thanks for making it to the last line of input.txt

I am running this on tcsh. I used the below one-liner :

Perl -p -e 'print "This line has special characters like $ \nI love this community"' if $. == 9' input.txt > output.txt 

The problem is that, in the above example, I know the number of last line. But in my code, the length of input.txt keeps changing. What changes should I make to the one-liner so that it works even if I don't give the last line number.

Note: please don't suggest using sed. I tried with sed and I was successful at performing the required task. However, my input file is around 325MB and sed is taking neraly 25 mins to do this task. I want it to be done in less than 5 mins.

Perl version being used : v5.10.1

2 Answers

Instead of fixed line number, check whether it is end of input file with eof

perl -pe 'print "This line has special characters like \$ \nI love this community\n" if eof' input.txt > output.txt

Using GNU sed to insert text before the last line of input:

 sed '$i This line has special characters like $\nI love this community' input.txt > output.txt
Related