Board logo

标题: [技术讨论] Perl版按规则替换文本 [打印本页]

作者: sxw    时间: 2011-10-18 23:40     标题: Perl版按规则替换文本

本帖最后由 sxw 于 2011-10-22 18:54 编辑

之前有601997526 写出了批版的,地址在http://www.bathome.net/thread-14419-1-1.html
现给出Perl版(欢迎讨论指正):
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. my %hash;
  5. open (my $in,"<","a.txt") or die;
  6. while (<$in>) {
  7. next if /^$/;
  8. chomp;
  9. my ($ori,$rep)=split /\|/;
  10. $hash{$ori}=$rep;
  11. }
  12. close $in;
  13. open my $fh,"<","text.txt" or die;
  14. while (<$fh>) {
  15. foreach my $key (keys %hash) {
  16.         my $regex=qr|\Q$key\E|;
  17.        s/$regex/$hash{$key}/g;
  18. }
  19. print;
  20. }
  21. close $fh;
复制代码
根据a.txt中的替换规则,目标文件为text.txt。
将text.txt中的每一行按如下规则替换:

如果出现|左边的字符全部替换为|右边的字符
a.txt类似下面的内容:(用|分隔,且其左右两边不再有其它的|)
  1. aaa|bbb_
  2. zzz|_aaa
  3. 123|321
  4. ___|---
  5. +++|$$$
  6. (((|)))
  7. <<<|>>>
  8. """|'''
  9. ```|""""
  10. ...|^^^
复制代码

作者: Batcher    时间: 2011-10-22 16:36

在顶楼给个链接吧,以便他人对照BAT版的代码。
作者: sxw    时间: 2011-10-22 17:33

回复 2# Batcher


    好的。。。




欢迎光临 批处理之家 (http://bbs.bathome.net/) Powered by Discuz! 7.2