如何使用公共字段提取行

时间:2013-10-04 19:07:27

标签: bash sed awk uniq

我有一个这样的文件 -

1 2 3
1 4 5
a z 3
a 3 4
a f g
b b g

我想将它分成多个文件(尽可能多组),每个文件都包含那些具有相同第一个字段的行。

 1 2 3
 1 4 5

 a z 3
 a 3 4
 a f g

 b b g

我该怎么做?我尝试了uniq --all-repeated=separate -w 32,但在查找重复项时,它会考虑完整行,而不仅仅是第一列。

2 个答案:

答案 0 :(得分:5)

这样的事情:

$ awk '{print > $1}' input

$ cat 1
1 2 3
1 4 5

$ cat a
a z 3
a 3 4
a f g

$ cat b
b b g

答案 1 :(得分:1)

稍微好一点的文件命名方法:

$ ls
file

$ awk '!($1 in a){a[$1]="file"++i}{print > a[$1]}' file

$ ls
file  file1  file2  file3

$ cat file1
1 2 3
1 4 5

$ cat file2
a z 3
a 3 4
a f g

$ cat file3
b b g