zoukankan      html  css  js  c++  java
  • perl 读取一个文件 替换文件的关键词 把数据替换到新的文件

    replace

    # replace
    #!/usr/bin/perl
    
    my @data = ();
    my ($fname ,$rp, $nfname)= @ARGV;
    my ($o, $n) = split("/", $rp);
    
    open(of, "<$fname") or die "$fname 文件打开失败!$!";
    while(<of>){
        chomp;
        $_ =~ s/$o/$n/;
        push @data, "$_
    ";
    }
    
    if(@data != 0) {
        chomp @data; # 砍掉最后的 
    
        open(nf_handle, ">$nfname") or die "Error: 文件$nfname打开失败$!";
        print nf_handle @data;
    }
    

    执行

    perl replace text.txt world/ajanuw ajanuw.txt
    

    text.txt

    hello world
    
    world asd
    
    123world456
    
    231
    

    ajanuw.txt

    hello ajanuw
    
    ajanuw asd
    
    123ajanuw456
    
    231
    

    改变源文件

    # replace
    #!/usr/bin/perl
    
    my @data = ();
    my ($fname ,$rp)= @ARGV;
    my ($o, $n) = split("/", $rp);
    
    open(rf, "<$fname") or die "$fname 文件打开失败! $!";
    while(<rf>){
        chomp;
        $_ =~ s/$o/$n/;
        push @data, "$_
    ";
    }
    
    if(@data != 0) {
        chomp @data; # 砍掉最后的 
    
        open(wf, "+>$fname") or die "$!";
        print wf @data;
    }
    
  • 相关阅读:
    [HNOI2002]营业额统计 (Splay)
    [POJ1664] 放苹果 (动态规划,组合数学)
    [AHOI2009]维护序列 (线段树)
    类型转换求和
    懒人创造方法
    编程的精义
    10-instanceof
    9-接口
    6-SUPER关键字
    5-重写与重载
  • 原文地址:https://www.cnblogs.com/ajanuw/p/9275371.html
Copyright © 2011-2022 走看看