1

是否有使用 awk、sort 或等于对多列 CSV 表的单列进行排序或反转的单步方法,同时保持其余部分的顺序相同?

例如,我有:

6, 45, 9
5, 47, 6
4, 46, 7
3, 48, 4
2, 10, 5
1, 11, 1

并希望拥有:

1, 45, 9
2, 47, 6
3, 46, 7
4, 48, 4
5, 10, 5
6, 11, 1  

因此,仅对第一列进行了排序,其余列按之前的顺序排列。

4

3 回答 3

2

这可能对您有用:

paste -d, <(cut -d, -f1 file | sort) <(cut -d, -f2- file)
于 2013-01-12T19:01:04.280 回答
1

awk 单行

awk -F, '{c[NR]=$1;l[NR]=$2", "$3}END{for(i=1;i<=NR;i++) print c[NR-i+1]", "l[i]}' file

测试

kent$  echo "6, 45, 9
5, 47, 6
4, 46, 7
3, 48, 4
2, 10, 5
1, 11, 1"|awk -F, '{c[NR]=$1;l[NR]=$2", "$3}END{for(i=1;i<=NR;i++) print c[NR-i+1]", "l[i]}'
1,  45,  9
2,  47,  6
3,  46,  7
4,  48,  4
5,  10,  5
6,  11,  1
于 2013-01-12T19:31:27.657 回答
0

If you have GNU awk here's a one liner:

$ gawk '{s[NR]=$1;c[NR]=$2 $3}END{for(i=0;++i<=asort(s);)print s[i] c[i]}' file
1,45,9
2,47,6
3,46,7
4,48,4
5,10,5
6,11,1

If not, here's an awk script that implements a simple bubble sort:

{ # read col1 in sort array, read others in col array
  sort[NR] = $1
  cols[NR] = $2 $3
}
END { # sort it with bubble sort
    do {
    haschanged = 0
    for(i=1; i < NR; i++) {
      if ( sort[i] > sort[i+1] ) {
    t = sort[i]
    sort[i] = sort[i+1]
    sort[i+1] = t
    haschanged = 1
      }
    }
  } while ( haschanged == 1 )

  # print it
  for(i=1; i <= NR; i++) {
      print sort[i] cols[i]
  }
}

Save it to a file sort.awk and do awk -f sort.awk file:

$ awk -f sort.awk file
1,45,9
2,47,6
3,46,7
4,48,4
5,10,5
6,11,1
于 2013-01-12T19:47:36.003 回答