Reputation: 355
I have a 2 fields in below file.
Field 1 is name and field 2 is transaction date.
I want unique name with lowest transaction date
cat abc.lst
John_20130201
David_20130202
Scott_20130203
Li_20130201
John_20130202
Scott_20130201
David_20130201
Li_20130204
Torres_20121231
output desired
John_20130201
Li_20130201
Scott_20130201
David_20130201
Torres_20121231
Upvotes: 1
Views: 113
Reputation: 7610
A pure bash
solution (not ordered by name):
declare -A hash
while IFS=_ read nam val; do
[[ -z "${hash[$nam]}" || $val < "${hash[$nam]}" ]] && hash[$nam]=$val
done <abc.lst
for i in ${!hash[*]}; do echo ${i}_${hash[$i]}; done
Output:
David_20130201
Li_20130201
John_20130201
Scott_20130201
Torres_20121231
Upvotes: 0
Reputation: 77105
sort -t_ -nk2 abc.lst | awk -F_ '!a[$1]++'
or save a pipe and do this -
awk -F_ '!a[$1]++' <(sort -t_ -nk2 abc.lst)
Upvotes: 4
Reputation: 42139
awk -F_ '{ l = lowest[$1]; if (!l || $2 < l) { lowest[$1] = $2 } }
END { for (name in lowest) print name FS lowest[name] }'
(if output order doesn't matter)
Upvotes: 0
Reputation: 195079
this one-liner selects those entries. but doesn't sort the output:
awk -F_ '$1 in a{a[$1]=$2>a[$1]?a[$1]:$2;next}{a[$1]=$2}
END{for(x in a)print x"_"a[x]}' file
Upvotes: 0
Reputation: 414
Use the sort
command:
cat abc.lst | sort -u -t_ -k1,1
And read about it on man sort
Upvotes: -2