[英]get 1 line with the same field in a file using shell script
我有一个文件,其内容如下:
onelab2.warsaw.rd.tp.pl 5
onelab3.warsaw.rd.tp.pl 5
lefthand.eecs.harvard.edu 7
righthand.eecs.harvard.edu 7
planetlab2.netlab.uky.edu 8
planet1.scs.cs.nyu.edu 9
planetx.scs.cs.nyu.edu 9
所以对于每一行,都有一个数字,我想要每个数字的第一行,因此对于上面的内容,我想得到:
onelab2.warsaw.rd.tp.pl 5
lefthand.eecs.harvard.edu 7
planetlab2.netlab.uky.edu 8
planet1.scs.cs.nyu.edu 9
我该如何实现? 我希望使用awk,sed等shell脚本。
这可能对您有用(GNU排序):
sort -nsuk2 file
对-k2
第二个字段-n
数字排序,保持-s
原始顺序,而-u
删除重复项。
为此,请使用awk
命令:
awk '{if(!a[$2]){a[$2]=1; print}}' file.dat
说明:
{
# 'a' is a lookup table (array) which will contain all numbers
# that have been printed so far. It will be initialized as an empty
# array on its first usage by awk. So you don't have to care about.
# $2 is the second 'column' in the line -> the number
if(!a[$2])
{
# set index in the lookup table. This way the if statement will
# fail for the next line with the same number at the end
a[$2]=1;
# print the whole current line
print
}
}
使用sort和uniq:
sort -n -k2 input | uniq -f1
perl -ane 'print unless $a{$F[1]}++' file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.