Lin*_*Lin 3 perl awk grep sed unique
我有这样一个文件:
1 2 3
4 5 6
7 6 8
9 6 3
4 4 4
Run Code Online (Sandbox Code Playgroud)
哪些单行可以将第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
Run Code Online (Sandbox Code Playgroud)
Cha*_*ens 10
在Perl之前 5.10
perl -lane 'print $F[0] unless $h{$F[0]}++' filename
Run Code Online (Sandbox Code Playgroud)
在Perl之后 5.10
perl -anE 'say $F[0] unless $h{$F[0]}++' filename
Run Code Online (Sandbox Code Playgroud)
替换0为要输出的列.
对于j_random_hacker,这里的实现将使用非常少的内存(但速度较慢,需要更多输入):
perl -lane 'BEGIN {dbmopen %h, "/tmp/$$", 0600; unlink "/tmp/$$.db" } print $F[0] unless $h{$F[0]}++' filename
Run Code Online (Sandbox Code Playgroud)
dbmopen在DBM文件(它创建或打开)和名为%h的哈希之间创建一个接口.存储在%h中的任何内容都将存储在光盘而不是内存中.使用unlink删除文件可确保文件在程序完成后不会停留,但对当前进程没有影响(因为根据POSIX规则,文件系统将打开的文件句柄视为真实文件).
更正:谢谢Mark Rushakoff.
$ cut -c 1 t.txt | sort | uniq
Run Code Online (Sandbox Code Playgroud)
要么
$ cut -c 1 t.txt | sort -u
1
4
7
9
Run Code Online (Sandbox Code Playgroud)