grep 输出从长到宽

Pao*_*ini 6 linux grep awk text-processing

我有一个模式文件,我想返回找到该模式的所有行号,但格式要宽,而不是长/传播。例子:

文件A.txt

Germany
USA
UK
Run Code Online (Sandbox Code Playgroud)

文件B.txt

USA
USA
Italy
Germany
UK
UK
Canada
Canada
Germany
Australia
USA
Run Code Online (Sandbox Code Playgroud)

我做了这样的事情:

grep -nf fileA.txt fileB.txt
Run Code Online (Sandbox Code Playgroud)

这给了我:

1:USA
2:USA
4:Germany
5:UK
6:UK
9:Germany
11:USA
Run Code Online (Sandbox Code Playgroud)

但是,我想要类似的东西:

Germany 4 9
USA 1 2 11
UK 5 6
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 11

使用 GNU datamash

$ grep -n -x -F -f fileA.txt fileB.txt | datamash -s -t : -g 2 collapse 1
Germany:4,9
UK:5,6
USA:1,2,11
Run Code Online (Sandbox Code Playgroud)

这首先使用 grep从中获取与 中的行fileB.txt完全匹配的行fileA.txt,并将匹配的行号与行本身一起输出。

除了问题中使用的选项之外,我还在使用-x-F。我这样做是为了避免从fileA.txt正则表达式 ( -F) 中,并匹配完整的行,而不是子字符串 ( -x)。

datamash然后,该实用程序将其解析为以 -:分隔的字段行 ( -t :),对其进行排序 (-s在第二个字段 ( -g 2; 国家)上对其进行 )并将第一个字段 ( collapse 1; 行号)折叠到每个国家的列表中。

然后,您显然可以使用tr ':,' '\t\t', 或以类似方式用空格替换冒号和逗号。

$ grep -n -x -f fileA.txt -F fileB.txt | datamash -s -t : -g 2 collapse 1 | tr ':,' '\t\t'
Germany 4       9
UK      5       6
USA     1       2       11
Run Code Online (Sandbox Code Playgroud)


αғs*_*нιη 8

使用awk

awk 'NR==FNR        { country[$0]= country[$0]? country[$0] FS NR: NR; next }
     ($0 in country){ print $0, country[$0] }' fileB fileA
Run Code Online (Sandbox Code Playgroud)

或者报告“count: 0 ”,以防fileA 中的countryName 没有出现在fileB 中,请执行以下操作:

awk 'NR==FNR        { country[$0]= country[$0]? country[$0] FS NR: NR; next }
     ($0 in country){ print $0, country[$0]; next } { print $0, "0" }' fileB fileA
Run Code Online (Sandbox Code Playgroud)


abo*_*uso 5

您可以将 grep 命令输出与 Miller ( https://github.com/johnkerl/miller ) 结合并运行

grep -nf fileA.txt fileB.txt | \
mlr --c2n --ifs ":" --implicit-csv-header --headerless-csv-output reorder -f 2  then \
nest --implode --values --across-records --nested-fs " " -f 1
Run Code Online (Sandbox Code Playgroud)

你将会有

Germany 4 9
USA 1 2 11
UK 5 6
Run Code Online (Sandbox Code Playgroud)