簡體   English   中英

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

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

我是 Perl 的新手。 請幫助我使用一個襯墊或 Perl proc 或 Perl 程序進行編程。 假設我的輸入文件是 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. 

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

我在 tcsh 上運行它。 我使用了以下單線:

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

問題是,在上面的例子中,我知道最后一行的編號。 但在我的代碼中,input.txt 的長度一直在變化。 我應該對單行進行哪些更改,以便即使我沒有給出最后一行編號也可以正常工作。

注意:請不要建議使用 sed。 我嘗試使用 sed 並成功執行所需的任務。 但是,我的輸入文件大約是 325MB,而 sed 需要 25 分鍾才能完成這項任務。 我希望它在不到 5 分鍾內完成。

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

不是固定的行號,而是用eof檢查它是否是輸入文件的結尾

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

使用 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