如何使用Perl从制表符分隔的文件中提取特定的列? [英] How can I use Perl extract a particular column from a tab-separated file?

查看:183
本文介绍了如何使用Perl从制表符分隔的文件中提取特定的列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Perl真的很陌生,一直在努力为这个问题找到解决方案.当我运行该程序时,没有任何错误,也没有显示任何内容.

I am really new at Perl and have been trying to piece together a solution for this. When I run this program I don't get any errors and it doesn't display anything.

代码如下:

#!/usr/bin/perl
open (DATA, "<test1.txt") or die ("Unable to open file");
use strict; use warnings;
my $search_string = "Ball";
while ( my $row = <DATA> ) {

    last unless $row =~ /\S/;
    chomp $row;
    my @cells = split /\t/, $row;

    if ($cells[0] =~/$search_string/){
        print $cells[0];
    }
}

我的测试数据文件如下

Camera Make     Camera Model    Text    Ball    Swing
a       b       c       d       e
f       g       h       i       j
k       l       m       n       o

在尝试使用实际的测试数据文件之前,我正在尝试查看其工作原理.

I am trying to see how this works before i use the actual test data file..

那么我该如何搜索"Ball"并让其返回"d i n"

So how do I search for say "Ball" and have it return "d i n"

推荐答案

尝试以下方法:

#!/usr/bin/perl
use strict;
use warnings;

open (DATA, "<test1.txt") or die ("Unable to open file");
my $search_string = "Ball";

my $header = <DATA>;
my @header_titles = split /\t/, $header;
my $extract_col = 0;

for my $header_line (@header_titles) {
  last if $header_line =~ m/$search_string/;
  $extract_col++;
}

print "Extracting column $extract_col\n";

while ( my $row = <DATA> ) {
  last unless $row =~ /\S/;
  chomp $row;
  my @cells = split /\t/, $row;
  print "$cells[$extract_col] ";
}

这篇关于如何使用Perl从制表符分隔的文件中提取特定的列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆