如何在现有文件的中间插入一行

时间:2011-11-30 05:43:36

标签: perl

  

考虑一个例子,我想在何时插入几行文字       特殊模式匹配(如果 $ line = ~m /这里的几行/ 那么       在下一行插入行):

*current file:*

"This is my file and i wanna insert few lines in here  and other
text of the file will continue."

*After insertion:*

"This is my file and i wanna insert few lines in here  this is my
new text which i wanted to insert and other text of the file will
continue."

这是我的代码:

my $sourcename = $ARGV[1];
my $destname = $ARGV[0];
print $sourcename,"\n";
print $destname,"\n";
my $source_excel = new Spreadsheet::ParseExcel;  
my $source_book = $source_excel->Parse($sourcename) or die "Could not open source Excel file $sourcename: $!";

my $source_cell;
#Sheet 1 - source sheet page having testnumber and worksheet number
my $source_sheet = $source_book->{Worksheet}[0];            #It is used to access worksheet

$source_cell = $source_sheet->{Cells}[1][0];                #Reads content of the cell;
my $seleniumHost = $source_cell->Value; 
print $seleniumHost,"\n";

open (F, '+>>',"$destname") or die "Couldn't open `$destname': $!";
my $line;

while ($line = <F>){
print $line;
if($line=~m/FTP/){
#next if /FTP/;
print $line;
print F $seleniumHost;}

6 个答案:

答案 0 :(得分:5)

perlfaq涵盖了这一点。 How do I change, delete, or insert a line in a file, or append to the beginning of a file?

文件是固定的数据块。它们的表现就像一张纸。你如何在一张纸的中间插入一条线?你不能,除非你留下空间。您必须重新复制整个内容,将您的行插入新副本。

答案 1 :(得分:3)

在perl单行中:

perl -ane 's/few lines in here  and other\n/this is my\nnew text which i wanted to insert and other /; s/continue./\ncontinue./; print ' FILE

如果你不想要单行,那么很容易在任何剧本中进行替换;)

答案 2 :(得分:0)

有人提到了Tie :: File,这是我要编辑文件的一个解决方案,但我通常使用File :: Slurp,它最近添加了edit_file和edit_file_lines subs。

答案 3 :(得分:0)

使用perl的就地编辑标志(-i),只要你可以键入文本字符串就可以很容易地使用Perl向现有文件添加行,例如(在你的情况下)“想要插入几行在这里“:

perl -pi -e 's{wanna insert few lines in here}{wanna insert few lines in here  this is my\nnew text which i wanted to insert }' filename

它会用你旧句子的副本(没有丢失)以及你想要注入的新东西覆盖旧句子(不要害怕)。如果您希望通过将“.backup”扩展名传递给-i标志,您甚至可以创建原始文件的备份:

perl -p -i'.backup' -e 's{wanna insert few lines in here}{wanna insert few lines in here  this is my\nnew text which i wanted to insert }' filename

有关Perl搜索和更多信息的更多信息替换功能可以在这里找到:

http://www.atrixnet.com/in-line-search-and-replace-in-files-with-real-perl-regular-expressions/

答案 4 :(得分:0)

您可以避免重复&#34;标记&#34;使用变量替换的文本。

echo -e "first line\nthird line" | perl -pe 's/(^first line$)/\1\nsecond line/'

答案 5 :(得分:0)

只要您知道这一行:

perl -ne 'if ($. == 8) {s//THIS IS NEW!!!\n/}; print;' 

显然,您必须使用-i进行实际更改 或:

perl -i -pe 'if($. == 8) {s//THIS IS NEW!!!\n/}' file