本文介绍了在没有标题&的csv文件中对行进行排序第一栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CSV文件,其中包含如下记录.

I've a CSV file containing records like below.

   id,h1,h2,h3,h4,h5,h6,h7 
   101,zebra,1,papa,4,dog,3,apple
   102,2,yahoo,5,kangaroo,7,ape

我想将行排序到该文件中,而没有标题和第一列.我的输出应该是这样.

I want to sort rows into this file without header and first column. My output should like this.

  id,h1,h2,h3,h4,h5,h6,h7
  101,1,3,4,apple,dog,papa,zebra
  102,2,5,7,ape,kangaroo,yahoo

我在AWK以下尝试过,但不知道如何排除标题和第一列.

I tried below AWK but don't know how to exclude header and first column.

awk -F"," ' {
s=""
for(i=1; i<=NF; i++) { a[i]=$i; }
for(i=1; i<=NF; i++)
{
for(j = i+1; j<=NF; j++)
{
if (a[i] >= a[j])
{
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
}
for(i=1; i<=NF; i++){ s = s","a[i]; }
print s
} 
' file

谢谢

推荐答案

如果perl还可以:

$ perl -F, -lane 'print join ",", $.==1 ? @F : ($F[0], sort @F[1..$#F])' ip.txt
id,h1,h2,h3,h4,h5,h6,h7 
101,1,3,4,apple,dog,papa,zebra
102,2,5,7,ape,kangaroo,yahoo

  • -F,表示,作为字段分隔符,结果保存在@F数组中
    • 请参见 https://perldoc.perl.org/perlrun.html#Command-切换以获取其他选项的详细信息
      • -F, to indicate , as field separator, results saved in @F array
        • See https://perldoc.perl.org/perlrun.html#Command-Switches for details on other options
          • ..是范围运算符,$#F将给出最后一个字段的索引
          • .. is range operator, $#F will give index of last field


          对于给定的标题,也可以对第一行进行排序,因此可以简化所需的逻辑


          For given header, sorting first line would work too, so this can simplify logic required

          $ perl -F, -lane 'print join ",", $F[0], sort @F[1..$#F]' ip.txt
          id,h1,h2,h3,h4,h5,h6,h7 
          101,1,3,4,apple,dog,papa,zebra
          102,2,5,7,ape,kangaroo,yahoo
          
          $ ruby -F, -lane 'print [$F[0], $F.drop(1).sort] * ","' ip.txt
          id,h1,h2,h3,h4,h5,h6,h7 
          101,1,3,4,apple,dog,papa,zebra
          102,2,5,7,ape,kangaroo,yahoo
          

          这篇关于在没有标题&amp;的csv文件中对行进行排序第一栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 09:03