【问题标题】:Extracting second column besides first unique column [closed]提取除第一个唯一列之外的第二列[关闭]
【发布时间】:2020-10-04 17:16:44
【问题描述】:

我有一个带有电子邮件 ID 和一些组织 ID 的文本文件 -

user1.org1@gmail.com 7001
user1.org1@gmail.com 5400
user1.org1@gmail.com A296
user1.org1@gmail.com 1008
user2@gmail.com 7018
user2@gmail.com 5420
user2@gmail.com A996
user3.org2@gmail.com 1018
user3.org2@gmail.com 7021

所有电子邮件 ID 均按字母顺序排序。这些数据存储在user_data.txt 文件中。 我想像这样在终端或文本文件中打印这样的输出 -

user1.org1@gmail.com 7001, 5400, A296, 1008
user2@gmail.com 7018, 5420, A996
user3.org2@gmail.com 1018, 7021

谁能帮我解决这个问题?

【问题讨论】:

  • 欢迎来到 Stack Overflow。 SO 是面向专业和热情的程序员的问答页面。请在您的问题中添加您自己的代码。您应该至少展示自己为解决这个问题所做的研究。
  • 这能回答你的问题吗? Merging word counts with Bash and Unix

标签: csv awk sed


【解决方案1】:

也在 shell 脚本中:

unset b
while read a c; do
    if [ "$b" = "$a" ]; then
        printf ', %s'  "$c"
    else
        [ "$b" ] && echo
        printf '%s %s'  "$a" "$c"
        b="$a"
    fi
done < user_data.txt
echo

【讨论】:

    【解决方案2】:

    使用永远有用的GNU datamash

    $ datamash -W -g1 collapse 2 < user_data.txt
    user1.org1@gmail.com    7001,5400,A296,1008
    user2@gmail.com 7018,5420,A996
    user3.org2@gmail.com    1018,7021
    

    (使用一个或多个空白字符而不是单个制表符作为输入列分隔符,按第一列分组并将每组的第二列值折叠到 CSV 列表中)。


    如果您没有datamash 并且无法安装它的替代方案:

    perl:

    perl -lane 'push @{$groups{$F[0]}}, $F[1];
                END {
                  for $g (sort keys %groups) {
                    print "$g ", join(",", @{$groups{$g}})
                }}' user_data.txt
    

    awk:

    awk '{ if ($1 in groups)
             groups[$1] = groups[$1] "," $2
           else
             groups[$1] = $2
         }
         END {
           PROCINFO["sorted_in"] = "@ind_str_asc" # Sort output if using GNU awk
           for (g in groups) print g, groups[g]
         }' user_data.txt
    

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 2018-04-04
      • 2013-08-01
      • 2015-01-18
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      • 2013-12-31
      相关资源
      最近更新 更多