将awk脚本翻译成perl

时间:2014-11-29 17:30:43

标签: regex perl awk

我试图将此代码翻译成perl。

 gawk '/^>c/ {OUT=substr($0,2) ".fa";print " ">OUT}; OUT{print >OUT}' your_input

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

Perl有一个实用程序可以为您执行此操作,名为a2p。如果您的脚本是script.awk,那么您将运行:

$ a2p script.awk

产生:

#!/usr/bin/perl
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
    if $running_under_some_shell;
            # this emulates #! processing on NIH machines.
            # (remove #! line above if indigestible)

eval '$'.$1.'$2;' while $ARGV[0] =~ /^([A-Za-z_0-9]+=)(.*)/ && shift;
            # process any FOO=bar switches

$, = ' ';       # set output field separator
$\ = "\n";      # set output record separator

while (<>) {
    chomp;  # strip record separator
    if (/^>c/) {
    $OUT = substr($_, (2)-1) . '.fa';
    &Pick('>', $OUT) &&
        (print $fh ' ');
    }
    ;

    if ($OUT) {
    &Pick('>', $OUT) &&
        (print $fh $_);
    }
}

sub Pick {
    local($mode,$name,$pipe) = @_;
    $fh = $name;
    open($name,$mode.$name.$pipe) unless $openammeamme}++;
}

要将其保存到文件,请使用重定向:

$ a2p script.awk > script.pl

Perl还提供了转换sed脚本的工具:s2p

答案 1 :(得分:2)

#!/usr/bin/perl

my ($outf,$OUT) ;
while(<>){
  if(/^>(c.*)/){ $OUT = "$1.fa";
                 close($outf) if $outf;
                 open($outf,">",$OUT);
                 print OUT " \n"}
  if($outf){ print $outf $_ }
}

如果输入为:

>caaa
sdf
sdff
>cbbb
ew
ew

创建2个文件:

==> caaa.fa <==
>caaa
sdf
sdff
==> cbbb.fa <==
>cbbb
ew
ew

答案 2 :(得分:1)

这个perl one liner应该等同于awk命令:

perl -ane 'if($F[0] =~ /^>c/){$OUT=substr($F[0],1).".fa"; if(OUT==null) {open(OUT,">$OUT");} print OUT " \n"} if ($OUT){print OUT $_} END{close(OUT)}' file

缩进命令行:

perl -ane 'if ($F[0] =~ /^>c/) {
       $OUT = substr($F[0], 1).".fa"; 
       if (OUT==null) { open(OUT, ">$OUT") }
       print OUT " \n"
    }
    if ($OUT) {
       print OUT $_
    }
    END{close(OUT)
}' file