等号后字符的替换

等号后字符的替换

cat a内容如下
myhostname = www.fw.com
mydomain = fw.com
test.pl a test.com
结果a的内容为:
myhostname = www.test.com
mydomain = test.com

不知道这个脚本怎么写?


[Copy to clipboard] [ - ]
CODE:
open(FN,$ARGV[0]); local $/=undef; $_=<FN>; $_ =~ s/fw/test/sg;

~]$ test.pl a >test.com
不管用,替换不了!
vi test.pl

[Copy to clipboard] [ - ]
CODE:
#!/usr/bin/perl
open(FN,$ARGV[0]); local $/=undef; $_=<FN>; $_ =~ s/fw/test/sg;

cat a
myhostname = www.fw.com
mydomain = fw.com


QUOTE:
原帖由 zw2002 于 2007-9-13 14:50 发表
不管用,替换不了!
vi test.pl

#!/usr/bin/perl
open(FN,$ARGV[0]); local $/=undef; $_=; $_ =~ s/fw/test/sg;

cat a
myhostname = www.fw.com
mydomain = fw.com

饿。。。我很无语,我只是写了关键片断,开头没写
还有,最后还要有句print $_;的啊。。
没这句,当然没用了,你自己加上再试验
还有,引用flw老大的话,“每个文件都要加上use strict; use warnings;”


[Copy to clipboard] [ - ]
CODE:
#! /usr/bin/perl -w
#        test.pl

use strict;        use warnings;
open(FN,$ARGV[0]); local $/=undef; $_=<FN>; $_ =~ s/fw/test/sg; print $_;

能不能通用些呢?不论等号后原来是什么都替换成,新输入的?
谢谢了
open(FILE, "<", $ARGV[0]) or die "Where the hell is $ARGV[0]?";
while (<FILE>) {
    s/(\s*=\s*(www\.)?).*/\1$ARGV[1]/;
    print $_;
}
close FILE;



如果要修改原来的文件, 就要再费点儿事了....
可是试试这么写 s/\w+\.com/$words.com/g
再具体,更多条件限制,就建议你自己看书了
直接修改原文件:

use strict;
use Tie::File;

tie my @lines, 'Tie::File', $ARGV[0] or die "Where the hell is $ARGV[0]?";
for (@lines) {
    s/(\s*=\s*(www\.)?).*/\1$ARGV[1]/;
}
untie @lines;


---------------------------------------------------------
# cat a
myhostname = www.test.com
mydomain = test.com

myhostname2 = www.123.com
mydomain2 = 123.com

myhostname3 = www.xxx.cn
mydomain3 = xxx.cn

# test.pl a test.net
# cat a
myhostname = www.test.net
mydomain = test.net

myhostname2 = www.test.net
mydomain2 = test.net

myhostname3 = www.test.net
mydomain3 = test.net
---------------------------------------------------------



QUOTE:
原帖由 Lonki 于 2007-9-13 15:41 发表
直接修改原文件:

use strict;
use Tie::File;

tie my @lines, 'Tie::File', $ARGV[0] or die "Where the hell is $ARGV[0]?";
for (@lines) {
    s/(\s*=\s*(www\.)?).*/\1$ARGV[1]/;
}
untie @lin ...

汗,原来他的 test.com 是第二个参数,看走眼了
谢谢楼上分享Tie::File,很好用的东东,而且说可以处理大文件,爽