【问题标题】:Linux - find content in a given lineLinux - 在给定行中查找内容
【发布时间】:2013-04-30 15:20:50
【问题描述】:

我有几个通用格式的文本文件

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

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

【问题讨论】:

    标签: perl sed awk grep


    【解决方案1】:

    壳牌

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

    Perl:

    $ 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
    

    【讨论】:

      【解决方案2】:

      您可能对此 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;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-07-06
        • 2012-12-04
        相关资源
        最近更新 更多