首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在perl脚本中调用awk

在perl脚本中调用awk
EN

Stack Overflow用户
提问于 2015-08-16 05:38:55
回答 1查看 435关注 0票数 0

我想输入一个文件,并使用文件每行中的元素调用awk,每行一个awk命令。现在,我正在使用perl脚本创建一个数组,并打印我想要运行的awk命令行。但是,我相信有一种更好的方法可以在perl脚本中实际运行awk命令。

文件如下所示:

代码语言:javascript
运行
复制
1 rs78641116 8374297 3374297 13374297
1 rs34269918 8424984 3424984 13424984
1 rs533123 29141155 24141155 34141155
1 rs1498232 30433951 25433951 35433951

代码如下:

代码语言:javascript
运行
复制
#! perl -w

open( my $file, "<", "sim.snps" ) or die $!;
while (<$file>) {
    my @snps=split;
    print "awk \'\$2>=$snps[3]\&\&\$2<=$snps[4]\{print\$1,\$2,\$3,\$4\}\' \..\/phasing_and_imputation\/1000GP_Phase3_chr$snps[0].legend > $snps[1]\.legend\n"
    }

输出awk命令:

代码语言:javascript
运行
复制
awk '$2>=3374297&&$2<=13374297{print$1,$2,$3,$4}' ../phasing_and_imputation/1000GP_Phase3_chr1.legend > rs78641116.legend
awk '$2>=3424984&&$2<=13424984{print$1,$2,$3,$4}' ../phasing_and_imputation/1000GP_Phase3_chr1.legend > rs34269918.legend
awk '$2>=24141155&&$2<=34141155{print$1,$2,$3,$4}' ../phasing_and_imputation/1000GP_Phase3_chr1.legend > rs533123.legend
awk '$2>=25433951&&$2<=35433951{print$1,$2,$3,$4}' ../phasing_and_imputation/1000GP_Phase3_chr1.legend > rs1498232.legend

有没有人有办法运行awk而不是打印awk命令?

EN

回答 1

Stack Overflow用户

发布于 2015-08-16 06:12:01

据我所知,这里有一个Perl解决方案来解决您的问题。

代码语言:javascript
运行
复制
#!/usr/bin/env perl

use strict;
use warnings;
use autodie;  # avoid a bunch of `or die` clauses

# First, load the criteria for splitting into the output files
my %files = ();

# extra block level wrapping the $ranges file access; file
# is automatically closed at the end of the block
{ 
  open my $ranges, '<', 'sim.snps';
  while (<$ranges>)  {
    (undef, my $key, undef, my ($min, $max)) = split;
    $files{$key} = { min => $min, max => $max };

    # go ahead and open the output file while we're here
    open $files{$file}{fh}, '>', "$key.legend";
  }
} # $ranges filehandle closed here

# another file-access block
{
  # open the data file
  open my $data, '<', '../phasing_and_imputation/1000GP_Phase3_chr1.legend';

  while (<$data>) {
    # split the data into fields
    my @f = split;

    # loop over the output files and write the relevant parts of this line
    # to the ones that want it
    while (my ($file, $data) = each %files) {
      if ($f[1] >= $data->{min}  && $f[1] <= $data->{max}) {
        print { $data->{fh} } join(' ', @f[0..3]), "\n";
      }
    }
  }
} # data file closed here

# close the output files
foreach my $data (values %files) {
  close $data->{fh};
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32029623

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档