我有一个这样的文件:
1 2 3
4 5 6
7 6 8
9 6 3
4 4 4
有哪些单行语句可以将第 n 列的唯一元素输出到另一个文件?
编辑:这是人们给出的解决方案列表。多谢你们!
cat in.txt | cut -d' ' -f 3 | sort -u
cut -c 1 t.txt | sort -u
awk '{ print $2 }' cols.txt | uniq
perl -anE 'say $F[0] unless $h{$F[0]}++' filename
在 Perl 之前5.10
perl -lane 'print $F[0] unless $h{$F[0]}++' filename
在 Perl 之后5.10
perl -anE 'say $F[0] unless $h{$F[0]}++' filename
替换0
为您要输出的列。
对于 j_random_hacker,这是一个使用很少内存的实现(但会更慢并且需要更多的输入):
perl -lane 'BEGIN {dbmopen %h, "/tmp/$$", 0600; unlink "/tmp/$$.db" } print $F[0] unless $h{$F[0]}++' filename
dbmopen在DBM文件(由它创建或打开)和名为 %h 的散列之间创建一个接口。存储在 %h 中的任何内容都将存储在磁盘上而不是内存中。使用取消链接删除文件可确保在程序完成后文件不会保留,但对当前进程没有影响(因为根据 POSIX 规则,文件系统将打开的文件句柄视为真实文件)。
更正:谢谢 Mark Rushakoff。
$ cut -c 1 t.txt | sort | uniq
或者
$ cut -c 1 t.txt | sort -u
1
4
7
9
取第三列的唯一值:
$ cat in.txt | cut -d' ' -f 3 | sort -u
3
4
6
8
cut -d' '
表示用空格分隔输入,-f 3
part表示取第三个字段。最后,sort -u
对输出进行排序,只保留唯一的条目。
假设您的文件是“cols.txt”,并且您想要第二列的唯一元素:
awk '{ print $2 }' cols.txt | uniq
您可能会发现以下文章有助于了解有关此类实用程序的更多信息:
如果使用 awk,则无需使用其他命令
awk '!_[$2]++{print $2}' file