在perl中编辑文件内容 [英] edit file contents in perl
问题描述
我想读取输入文件,然后删除与正则表达式匹配的行.并保存了该行的文件.
I would like to read an input file and then delete a line if it matches my regex. and have the file saved without that line.
我写了
open(my $fh, '<:encoding(UTF-8)', $original_file_path or die "Could not open file $original_file_path $!";
while (my $line = <$fh> ) {
chomp $line;
if ($line ~=/myregex/){
delete line from file
}
}
谢谢
推荐答案
您可以使用-i
标志来修改文件 .
You can modify a file in place by using -i
flag.
在您的情况下,一个简单的班轮就可以了:
In your case, a simple one liner would do:
perl -i -ne 'print unless /myregex/' the_name_of_your_file
如PerlDuck所述,如果您希望保留原始文件的副本,则可以:在-i
标志后添加扩展名,例如-i.bak
或-i~
,然后原始文件将与此保留在一起.扩展名之后.
As mentioned by PerlDuck, if you wish to keep a copy the original file, it's possible: add an extension after the -i
flag, like -i.bak
or -i~
, and then original file will be kept with this extension after its name.
您可以在 perlrun 上找到有关就地文件修改的更多信息.
You can find more information about inplace file modification on perlrun.
请注意,如果您使用的是Windows (MS-DOS),则需要指定备份文件的扩展名,以后可以随意删除.请参阅此
Note that if you are using Windows (MS-DOS), you will need to specify an extension for the backup file, that you are free to delete afterward. See this link.
通过将$^I
设置为不同于undef
的值,可以在脚本中获得相同的行为.例如:
You can obtain the same behavior in a script by setting $^I
to a value different than undef
. For instance:
#!/usr/bin/perl
use strict;
use warnings 'all';
{
local @ARGV = ( $original_file_path );
local $^I = ''; # or set it to something else if you want to keep a backup
while (<>) {
print unless /myregex/
}
}
我已经使用过local @ARGV
,所以如果您在@ARGV
中已经有了某些东西,就不会造成任何麻烦.如果@ARGV
为空,那么push @ARGV, $original_file_path
也可以.
I've used local @ARGV
so if you already had something in @ARGV
, it won't cause any troubles. If @ARGV
was empty, then push @ARGV, $original_file_path
would be fine too.
但是,如果您要在脚本中做更多的事情,您可能会希望使用完整脚本而不是单行脚本.在这种情况下,您应该阅读输入文件,然后将要保留的行打印到另一个文件,然后将第二个文件move
复制到第一个文件.
However, if you have more stuff to do in your script, you might prefer a full script over a one-liner. In that case, you should read your input file, and print the lines you want to keep to another file, then move
the second file to the first.
这篇关于在perl中编辑文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!