niuguohao 发表于 2018-04-25 22:36

求助:perl 匹配替换的问题

我有一个文件A,里面有两列,如下:
384208chr1
384206chr2
384197chr3

……

还有另一个文件B,想把B中所有A里面第一列的内容替换为对应的第二列的内容,该怎么写脚本呢?
例如:
aaaaaaa384208bbbb
aaaaaaa384197ccccc
替换为:
aaaaaaachr1bbbb
aaaaaaachr2ccccc

A文件大约2万行,用sed似乎不太合适;
A里面都是一一对应切不重复的,本来把A写成了哈希,然后替换B文件中的,但一直报错,求各位大神帮忙!!!

niuguohao 发表于 2018-04-25 23:13

以下是我自己写的,刚刚开始学,写的漏洞百出,请各位帮忙指点!
#!/usr/bin/perl
use strict;
my %hash_data;
open(FL,"name5");
while(<FL>)
{
      chomp();
      my ($dkey,$dval)= split(/\s+/,$_);
      $hash_data{$dkey}=$dval;
}
close(FL);
open (FF,"out5.recode.vcf");
while (<FF>){
      s/$tkey/$hash_data{$tkey}/ while $_ =~/$tkey/;
print $_;
}

kernel69 发表于 2018-04-26 08:48

回复 1# niuguohao

# perl -lne '@ARGV==1 ? do{@F=split;$h{$F}=$F} : do{s/(\d+)/$h{$1}/e and print}' a b
aaaaaaachr1bbbb
aaaaaaachr3ccccc
#


niuguohao 发表于 2018-04-26 10:16

回复 3# kernel69

感谢大神帮助,我还有问题,按照这样输出的结果好像仅是发生替换的行,如果想同时把没有替换过的行也输出该怎样写呢?


niuguohao 发表于 2018-04-26 11:26

#!/usr/bin/perl
my %hash;
open(FL,"name5");
while(<FL>)
{
      chomp();
      my ($key,$val)= split(/\t+/,$_);
      $hash{$key}=$val;
      }
open (FF,"out5.recode.vcf");
while (<FF>){
      s/DF(\d+)\.1/$hash{$key}/e while $_=~/DF(\d+)\.1/;
      print $_;
      }
close(FL);
close(FF);

重新改了改,现在要替换的字符都被替换成空了……
我前面说的不对,,,文件A应该是这样的:
DF384205.1      Sme2.5_33732.1
DF384204.1      Sme2.5_33731.1
DF384203.1      Sme2.5_33728.1
…………



烦劳各位大神帮忙看看

kernel69 发表于 2018-04-26 12:27

回复 4# niuguohao

那就把and替换成;
perl -lne '@ARGV==1 ? do{@F=split;$h{$F}=$F} : do{s/(\d+)/$h{$1}/e;print}' a b

niuguohao 发表于 2018-12-25 20:30

#!/usr/bin/perl
my %hash;
open(FL,"name5");
while(<FL>)
{
      chomp();
      my ($key,$val)= split(/\t+/,$_);
      $hash{$key}=$val;
      }
open (FF,"out5.recode.vcf");
while (<FF>){
      s/DF(\d+)\.1/$hash{$key}/e ;
      print $_;
      }
close(FL);
close(FF);
页: [1]
查看完整版本: 求助:perl 匹配替换的问题