• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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!

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
FATAL ERROR: please install the following Perl modules before executing scripts/ ...发布时间:2022-07-22
下一篇:
perl输出中文有乱码发布时间:2022-07-22
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap