如何修剪文件 - 使用相同的值删除列 [英] how to trim file - remove the columns with the same value

查看:101
本文介绍了如何修剪文件 - 使用相同的值删除列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想你在用相同的值删除列修剪的文件帮助。

 #文件我有(制表符分隔,数以百万计列)
插孔1 5 9
约翰福音3 5 0
丽莎4 5 7


 #我想要的文件(删除列在所有行的值相同)
插孔1 9
约翰·3 0
丽莎4 7

能否请您给我这个问题的任何指示?我preFER一个awk或者sed的解决方案,或者一个Perl的解决方案。

在此先感谢。
最好的,


解决方案

 #!的/ usr / bin中/ perl的
$ / =\\ t的;
开(R,<,/ tmp目录/文件名)||死;
而(小于; R GT)
{
  接下来,如果(($%4)== 3);
  打印;
}

好了,这是假设它是第三列。如果是按值:

 #!的/ usr / bin中/ perl的
$ / =\\ t的;
开(R,<,/ tmp目录/文件名)||死;
而(小于; R GT)
{
  接下来,如果(($ _ == 5);
  打印;
}

使用问题编辑,OP的欲望变得清晰起来。怎么样:

 #!的/ usr / bin中/ perl的
开(R,<,/ tmp目录/文件名)||死;
我的第一个$ = 1;
我(@cols);
而(小于; R GT)
{
  我(@this)=拆分(/ \\ t /);
  如果($ == 1)
  {
    @cols = @this;
  }
  其他
  {
    为(我的$ X = 0; $ X< = $#COLS; $ X ++)
    {
      如果(定义($ COLS [$ X])及和放大器;!($ COLS [$ X] ~~ $此[$ X]))
      {
        $ COLS [$ X] =民主基金;
      }
    }
  }
  接下来,如果(($ _ == 5));
#打印;
}
接近(R);
我(@del);
打印删除列;
为(我的$ X = 0; $ X< = $#COLS; $ X ++)
{
  如果(定义($ COLS [$ X]))
  {
    打印$ X($ COLS [$ X]),
    推(@德尔,$ X-INT(@del));
  }
}
打印\\ n;开(R,<,/ tmp目录/文件名)||死;
而(小于; R GT)
{
  终日啃食;
  我(@this)=拆分(/ \\ t /);  我的foreach $山坳(@del)
  {
    拼接(@此,$关口,1);
  }  打印连接(\\ t的,这@)\\ N。
}
接近(R);

I would like your help on trimming a file by removing the columns with the same value.

# the file I have (tab-delimited, millions of columns)
jack 1 5 9
john 3 5 0
lisa 4 5 7


# the file I want (remove the columns with the same value in all lines)
jack 1 9
john 3 0
lisa 4 7

Could you please give me any directions on this problem? I prefer a sed or awk solution, or maybe a perl solution.

Thanks in advance. Best,

解决方案

#!/usr/bin/perl
$/="\t";
open(R,"<","/tmp/filename") || die;
while (<R>)
{
  next if (($. % 4) == 3);
  print;
}

Well, this was assuming it was the third column. If it is by value:

#!/usr/bin/perl
$/="\t";
open(R,"<","/tmp/filename") || die;
while (<R>)
{
  next if (($_ == 5);
  print;
}

With the question edit, OP's desires become clear. How about:

#!/usr/bin/perl
open(R,"<","/tmp/filename") || die;
my $first = 1;
my (@cols);
while (<R>)
{
  my (@this) = split(/\t/);
  if ($. == 1)
  {
    @cols = @this;
  }
  else
  {
    for(my $x=0;$x<=$#cols;$x++)
    {
      if (defined($cols[$x]) && !($cols[$x] ~~ $this[$x]))
      {
        $cols[$x] = undef;
      }
    }
  }
  next if (($_ == 5));
#  print;
}
close(R);
my(@del);
print "Deleting columns: ";
for(my $x=0;$x<=$#cols;$x++)
{
  if (defined($cols[$x]))
  {
    print "$x ($cols[$x]), ";
    push(@del,$x-int(@del));
  }
}
print "\n";

open(R,"<","/tmp/filename") || die;
while (<R>)
{
  chomp;
  my (@this) = split(/\t/);

  foreach my $col (@del)
  {
    splice(@this,$col,1);
  }

  print join("\t",@this)."\n";
}
close(R);

这篇关于如何修剪文件 - 使用相同的值删除列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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