perl 对源文件内容修改 方法整理

1, 利用Tie::File模块来直接对文件内容进行修改。

#!/usr/bin/perl -w

my
$std="F160"; my $fast="FAST"; my $file=shift @ARGV;
updatefile2($file);

sub updatefile2 { if(defined($file)) { use Tie::File; tie my @contents, 'Tie::File', "$file" or die "can't open $!\n"; for(@contents){ s/(.*[,])$std([,].*)/${1}$fast${2}/g } untie @contents; exit 0; } else { print "please provide file name!\n"; }

2, 直接命令:

perl -pi -e 's/(.*[,])$std([,].*)/${1}$fast${2}/g' $file

3, 文件小的话,读取修改后再覆盖进去:

sub updatefile3 {
 open FILE, $file or die "$!";
 my @oldfile=<FILE>;
 close FILE;
 foreach(@oldfile) {
   s/,$std,/,$fast,/g;
    #s/,$fast,/,$std,/g;
 }
 open FILE, ">", $file or die "$!";
 print FILE @oldfile;
 close FILE;
}

4, 通过创建临时文件方式:

sub updatefile1 {
if(defined($file)) {
  my $buffer="$file buffer"; # save the new data
  my $bak = "$file.bak";  #back up the old data
  open OPENFILE, "<", "$file" or die "can not open file:$!\n";
  open OPENFILEE, ">", "$buffer" or die "can not open file:$!\n";
  $^I=".bak";
  while(<OPENFILE>) {
  chomp;
    s/,$std,/,$fast,/g;
    #s/,$fast,/,$std,/g;
    print "$_\n";
    print OPENFILEE "$_\n" or die "can not write to $buffer: $!";
  }
  close OPENFILE; close OPENFILEE;
  rename("$file", "$bak") or die "can not rename $file to $bak: $!";
  rename("$buffer", "$file") or die "can not rename $buffer to $file: $!";
} else {
  print "please provide file name!\n";
}

}

5,一行一行的修改:

比如x.txt内容如下:
hello
world!

执行下面这个程序:
open(FH,"+<x.txt");
$line=<FH>;; #跳过第1行
$pos=tell(FH); #记录第2行起始位置
$line=<FH>;; #读入第2行内容
$line=~s/world/cosmos/; #进行一些更改
seek(FH,$pos,SEEK_SET); #重新定位到第2行起始位置
print FH $line; #更新第2行内容
close(FH);

然后x.txt就是这样了:
hello
cosmos!

要注意的地方就是更新文件时要用"+<"打开。

原文地址:https://www.cnblogs.com/cade/p/3447516.html