perl 替换文本文件内容

各位:我在WinXP环境下,试图将test.txt中的所有1234替换称ABCD。但目前只能将从句柄读出来的变量修改,而不能修改文件test.txt。请问如何才能修改到test.txt呀??求助……

1.批量替换用sed:

sed 's/a/b/g' ##将a 换成b

2.批量替换文件内容方法,命令结构如下:

find -name '要查找的文件名' | xargs perl -pi -e 's|被替换的字符串|替换后的字符串|g'
3.下面例子将当前目录及所有子目录下的所有pom.xml文件的”http://repo1.maven.org/maven2“替换为”http://localhost:8081/nexus/content/groups/public“。

find -name 'pom.xml' | xargs perl -pi -e
's|http://repo1.maven.org/maven2|http://localhost:8081/nexus/content/groups/public|g'

4.这里用到了Perl语言perl -pi -e

5.在Perl 命令中加上-e 选项,使用Perl 实现一些强大的、实时的转换。
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-03-18

是的,只有从文件读出修改,并且保存为别的文件,然后在修改名字,例如:

open(F1,'<test.txt');
open(F2,'>test.txt.tmp');
while ($s=<F1>){
    $s =~ s/1234/ABCD/g;
    print F2, $s;
}
close(F2);
close(F1);

unlink('test.txt');
rename('test.txt.tmp','test.txt');

本回答被网友采纳
第2个回答  推荐于2016-09-13
sed -i 's/1\.0\.0/2.2.3/g' /resource/1.rc

这个比 perl 快。

#!/usr/bin/env perl

use strict;
use warnings;

my $from = '1.0.0';
my $to = '2.2.3';

my $file = '1.rc';
my $fileout = '2.rc';

open my $fh , $file or die "couldn't open $file\n";
open my $out , ">$" or die "couldn't write $";

while ( <$fh> ) {
s/1\.0\.0/2.2.3/;
print $out $_;
}

本回答被提问者采纳
第3个回答  2011-09-27
open (FILE,"test.txt")||die "can't open test";
while(<FILE>){
s/1234/ABCD/;
print $line;
}
close (FILE);
第4个回答  2011-09-23
--这话说的,你吧修改过后的句柄写回文件里不就是了....

open FW, "> newfile.txt"
or die "Can't open file for write";
while (<TXT>) {
s/1234/ABCD/ ;
print FW;
}
相似回答