简体   繁体   English

Perl 一行最后添加文本但大文件的一行

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

I am novice to Perl.我是 Perl 的新手。 Please help me in the programming using either one liner or a Perl proc or a Perl program.请帮助我使用一个衬垫或 Perl proc 或 Perl 程序进行编程。 Let's suppose my input file is input.txt and its contents are as follows:假设我的输入文件是 input.txt,其内容如下:

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:下面是我要生成的 output 文件:

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.我在 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.但在我的代码中,input.txt 的长度一直在变化。 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.注意:请不要建议使用 sed。 I tried with sed and I was successful at performing the required task.我尝试使用 sed 并成功执行所需的任务。 However, my input file is around 325MB and sed is taking neraly 25 mins to do this task.但是,我的输入文件大约是 325MB,而 sed 需要 25 分钟才能完成这项任务。 I want it to be done in less than 5 mins.我希望它在不到 5 分钟内完成。

Perl version being used: v5.10.1 Perl 正在使用的版本:v5.10.1

Instead of fixed line number, check whether it is end of input file with eof不是固定的行号,而是用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:使用 GNU sed在输入的最后一行之前插入文本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM