首页 > 解决方案 > 根据 shell 中的某个字段在 csv 中查找唯一的出现

问题描述

我有一个文件emails.csv

>cat emails.csv
1,joe,joe@gmail.com,32
2,jim,jim@hotmail.fr,23
3,steve,steve_smith@temporary.com.br,45
4,joseph,joseph@protonmail.com,23
5,jim,jim29@bluewin.ch,29
6,hilary,hilary@bluewin.ch,32

当我找到具有相同最后一个字段(年龄)的另一个条目时,我只想保留第一个条目 - 基于最后一个字段的唯一条目。我想要的输出是:

1,joe,joe@gmail.com,32
2,jim,jim@hotmail.fr,23
3,steve,steve_smith@temporary.com.br,45
5,jim,jim29@bluewin.ch,29

以下脚本能够进行过滤:

> cut -d, -f4 emails.csv |
> while read age1;
> do line=1;continue_loop=1 cut -d, -f4 emails.csv | while read age;
> do if [[ $age1 == $((age)) ]] && [[ $continue_loop == $1 ]];
> then cat emails.csv | head -n $line | tail -n 1;
> continue_loop=0; fi;
> let line++;
> done;
> done | sort

但是,我正在寻找一种不需要两个循环的解决方案,因为这似乎有点过于复杂。

标签: bashshellcutuniq

解决方案


sort -t, -k4 emails.csv | sed -e 's/,/ /g' | uniq -f3 | sed -e 's/ /,/g'

但似乎 Perl 或 Pyhon 等其他语言会帮助您编写更稳定且不那么丑陋的解决方案


推荐阅读