0

我有几个具有一般格式的文本文件

0
0
0
0
125
0
0
0
0
0
0
3211
0
0

0
0

首先,我想确定 file1.txt 中的哪些行包含非零元素

grep -ne '^[1-9]' file1.txt | cut -f 1 d:

然后,我想遍历 file1.txt、file2.txt 和 file3.txt 中的这些行号,并将找到的数字粘贴到具有该格式的新文件中。每个文本文件每行有一个数字,尽管偶尔的行只有一个换行符

file1  file2   file3
125    a num   a num
3211   a num   a num

我会使用 paste 命令将每个结果附加到我的新文本文件中。但是,我不确定如何 grep 获取特定行号的内容。任何帮助,将不胜感激

4

2 回答 2

2

$ paste -d "  " f1 f2 f3 | grep -v "^0 "
1 101 201
3 103 203
11 111 211

珀尔:

$ cat script.pl
open(my $f1, "<", "f1")||die $!; 
open(my $f2, "<", "f2")||die $!; open(my $f3, "<", "f3")||die $!;
while (my $line1=<$f1>) {
    chomp $line1; 
    my $line2 = <$f2>; chomp $line2; my $line3 = <$f3>; chomp $line3;
    next if $line1 =~ /^0*$/;
    print "$line1 $line2 $line3\n"
}
$ perl script.pl
1 101 201
3 103 203
11 111 211

数据:

$ cat f1
0
0
1
0
3
0
11
$ cat f2
0
0
101
0
103
0
111
$ cat f3
0
0
201
0
203
0
211
于 2013-04-30T15:48:13.933 回答
0

您可能对此 Perl 版本感兴趣。

use strict;
use warnings;

use Tie::File;

my @rows;
my @i;
my @files = qw/ file1.txt file2.txt file3.txt /;

for my $file (@files) {
  tie my @file, 'Tie::File', $file or die qq{Couldn't open file "$file": $!};
  my @i = grep $file[$_], 0 .. $#file unless @i;
  my @column = @file[@i];
  push @{$rows[$_]}, $column[$_] for 0 .. $#column;
}

print join("\t", @files), "\n";
print join("\t", @{$rows[$_]}), "\n" for 0 .. $#rows;
于 2013-04-30T16:09:46.517 回答