Bash 对具有特定列的文件进行排序和uniq,并仅保留给定文件中的第一个值

Bash 对具有特定列的文件进行排序和uniq,并仅保留给定文件中的第一个值,bash,sorting,uniq,Bash,Sorting,Uniq,我有样本文件 $ cat a.csv a,1,c b,1,d d,3,a s,2,c a,3,s 必需的 a,1,c s,2,c a,3,s 它必须删除uniq之后的所有其他值,但只保留第一个值 排序与uniq a,1,c s,2,c a,3,s 我尝试了sort-k2-na.csv但是得到了这个结果 a,1,c a,3,s b,1,d d,3,a s,2,c 当我尝试sort-k2-na.csv | uniq-d时,我得到了空白结果 $ sort -t, -u -k2,2 a.csv

我有样本文件

$ cat a.csv
a,1,c
b,1,d
d,3,a
s,2,c
a,3,s
必需的

a,1,c
s,2,c
a,3,s
它必须删除uniq之后的所有其他值,但只保留第一个值

排序与uniq

a,1,c
s,2,c
a,3,s
我尝试了
sort-k2-na.csv
但是得到了这个结果

a,1,c
a,3,s
b,1,d
d,3,a
s,2,c
当我尝试
sort-k2-na.csv | uniq-d
时,我得到了空白结果

$ sort -t, -u -k2,2 a.csv 
a,1,c
s,2,c
d,3,a
  • -t,
    指定
    作为分隔符
  • -u
    仅获取唯一的条目
  • -k2,2
    使用第二列作为排序标准
  • -t,
    指定
    作为分隔符
  • -u
    仅获取唯一的条目
  • -k2,2
    使用第二列作为排序标准
    • awk中的另一个:

      $ awk -F, '{if(!($2 in a)||$0<a[$2])a[$2]=$0}END{for(i in a)print a[i]}' file
      
      解释:

      $ awk -F, '                                  # fields comma-separated
      {
          if(!($2 in a) || $0<a[$2])               # if $2 unseen or record < stored record
              a[$2]=$0                             # store it to a hash
      }
      END {                                        # after processing the file
          # PROCINFO["sorted_in"]="@ind_num_desc"  # sort output on $2 if using GNU awk
          for(i in a)                              # iterate all stored instances in a 
              print a[i]                           # and output
      }' file
      
      $awk-F',#字段以逗号分隔
      {
      如果(!(a中的$2)| |$0另一个awk:

      $ awk -F, '{if(!($2 in a)||$0<a[$2])a[$2]=$0}END{for(i in a)print a[i]}' file
      
      解释:

      $ awk -F, '                                  # fields comma-separated
      {
          if(!($2 in a) || $0<a[$2])               # if $2 unseen or record < stored record
              a[$2]=$0                             # store it to a hash
      }
      END {                                        # after processing the file
          # PROCINFO["sorted_in"]="@ind_num_desc"  # sort output on $2 if using GNU awk
          for(i in a)                              # iterate all stored instances in a 
              print a[i]                           # and output
      }' file
      
      $awk-F',#字段以逗号分隔
      {
      
      如果(!(a中的$2)| |$0,则输出与“所需”不完全相同(请参见输出的最后一行)。我不确定这是否真的很重要,或者OP只是想在第二个字段的每个值中取一个。@WDC你能解释一下排序标准吗?我想你想要
      sort a.csv | sort-t,-u-k2,2
      ,但不是sure@Sundeep,说实话,我在我的脚本中使用了你的代码…因为在排序之后,无论谁删除都无关紧要,第一个还是最后一个输出不完全符合“要求”(见输出的最后一行)。我不确定这是否真的很重要,或者OP只是想在第二个字段的每个值中取一个。@WDC你能解释一下排序标准吗?我想你想要
      sort a.csv | sort-t,-u-k2,2
      ,但不是sure@Sundeep,说实话,我在我的脚本中使用了你的代码…因为在排序之后,删除谁最重要,第一个还是最后一个。