在Perl中,如何在文件中更改,删除或插入一行,或者追加到文件的开
我想通过修改,删除或插入行或追加到文件的开头来更改文件的内容。如何在Perl中执行此操作?
这是0700的question。我们是importing the perlfaq to Stack Overflow。 解决方法
(这是
official perlfaq answer,减去任何后续编辑)
从文本文件中插入,更改或删除行的基本思想 执行这些任务的Perl程序是打开文件的基本形式, open my $in,'<',$file or die "Can't read old file: $!"; open my $out,'>',"$file.new" or die "Can't write new file: $!"; while( <$in> ) { print $out $_; } close $out; 在该基本形式中,添加您需要插入,更改或 要在开始前添加行,请在输入前打印这些行 open my $in,"$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the topn"; # <--- HERE'S THE MAGIC while( <$in> ) { print $out $_; } close $out; 要更改现有行,请插入代码以修改其中的行 open my $in,"$file.new" or die "Can't write new file: $!"; print $out "# Add this line to the topn"; while( <$in> ) { s/b(perl)b/Perl/g; print $out $_; } close $out; 要更改特定行,输入行号$。是有用的。 while( <$in> ) # print the lines before the change { print $out $_; last if $. == 4; # line number before change } my $line = <$in>; $line =~ s/b(perl)b/Perl/g; print $out $line; while( <$in> ) # print the rest of the lines { print $out $_; } 要跳过线,请使用循环控件。此示例中的下一个将跳过 while( <$in> ) { next if /^s+#/; # skip comment lines last if /^__(END|DATA)__$/; # stop at end of code marker print $out $_; } 做同样的事情删除一个特定的行,使用下一个跳过 while( <$in> ) { next unless $. % 5; print $out $_; } 如果由于某种奇怪的原因,您真的想要一次看到整个文件 open my $in,$file or die "Can't read old file: $!" open my $out,"$file.new" or die "Can't write new file: $!"; my @lines = do { local $/; <$in> }; # slurp! # do your magic here print $out @lines; 模块如File::Slurp 您也可以使用Perl one-liners来就地修改文件。下列 perl -pi -e 's/Fred/Barney/' inFile.txt 要备份inFile.txt,请输入文件扩展名来添加: perl -pi.bak -e 's/Fred/Barney/' inFile.txt 要更改第五行,您可以添加一个测试检查$。,输入 perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt 要在某行之前添加行,您可以在之前添加一行(或行!) perl -pi -e 'print "Put before third linen" if $. == 3' inFile.txt 您甚至可以在文件的开头添加一行,因为当前行 perl -pi -e 'print "Put before first linen" if $. == 1' inFile.txt 要在文件中已经有一行之后插入一行,请使用-n开关。它的 perl -ni -e 'print; print "Put after fifth linen" if $. == 5' inFile.txt 要删除行,只打印您想要的行。 perl -ni -e 'print unless /d/' inFile.txt … 要么 … perl -pi -e 'next unless /d/' inFile.txt (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |