簡體   English   中英

一起使用grep和awk

[英]Using grep and awk together

我有一個文件(A.txt),其中有4列數字,另一個文件是3列數字(B.txt)。 我需要解決以下問題:

  1. 查找A.txt中所有第三行的數字都出現在B.txt第三列中任意位置的所有行。

  2. 假設我在目錄中有很多文件,例如A.txt。 我需要為該目錄​​中的每個文件運行此文件。

我該怎么做呢?

您永遠都不會看到有人同時使用grepawk ,因為grep可以做的任何事情,您也可以在awk做:

Grep和Awk

grep "foo" file.txt | awk '{print $1}'

僅使用Awk:

awk '/foo/ {print $1}' file.txt

我得把它從胸口拿下來。 現在解決您的問題...

Awk是一種編程語言,它假定通過一組文件中的所有行進行單個循環。 而且,您不想這樣做。 相反,您希望將B.txt視為特殊文件,並循環瀏覽其他文件。 通常需要像Python或Perl這樣的東西。 (較舊的BASH版本無法處理哈希鍵數組,因此這些版本的BASH無法正常工作。)但是, slitvinov似乎找到了答案。

無論如何,這是一個Perl解決方案:

use strict;
use warnings;
use feature qw(say);
use autodie;

my $b_file = shift;
open my $b_fh, "<", $b_file;

#
# This tracks the values in "B"
#
my %valid_lines;
while ( my $line = <$b_file> ) {
    chomp $line;
    my @array = split /\s+/, $line;
    $valid_lines{$array[2]} = 1;   #Third column
}
close $b_file;

#
# This handles the rest of the files
#
while ( my $line = <> ) {  # The rest of the files
   chomp $line;
   my @array = split /\s+/, $line;
   next unless exists $valid_lines{$array[2]};  # Next unless field #3 was in b.txt too
   say $line;
}

這是一個例子。 創建以下文件並運行

awk -f c.awk B.txt A*.txt 

奧克

FNR==NR {
    s[$3]
    next
}

$3 in s {
    print FILENAME, $0
}

A1.txt

1 2 3
1 2 6
1 2 5

A2.txt

1 2 3
1 2 6
1 2 5

B.txt

1 2 3
1 2 5
2 1 8

輸出應為:

A1.txt 1 2 3
A1.txt 1 2 5
A2.txt 1 2 3
A2.txt 1 2 5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM