sort.sh 959 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/bin/bash
  2. # 输入检查
  3. if [ $# -lt 2 ]; then
  4. echo "用法: $0 <CSV文件> <排序列名> [numeric]"
  5. echo "示例: $0 data.csv Age numeric"
  6. exit 1
  7. fi
  8. input_file="$1"
  9. sort_column="$2"
  10. numeric_sort="${3:-text}"
  11. # 检查文件是否存在
  12. if [ ! -f "$input_file" ]; then
  13. echo "错误: 文件 '$input_file' 未找到"
  14. exit 1
  15. fi
  16. # 提取标题行
  17. header=$(head -n 1 "$input_file")
  18. # 确定列索引
  19. column_index=$(echo "$header" | awk -F, -v col="$sort_column" '{
  20. for(i=1; i<=NF; i++) {
  21. if ($i == col) {
  22. print i
  23. exit
  24. }
  25. }
  26. print -1
  27. }')
  28. # 列名检查
  29. if [ "$column_index" -eq -1 ]; then
  30. echo "错误: 列 '$sort_column' 在标题中未找到"
  31. exit 1
  32. fi
  33. # 设置排序参数
  34. sort_options="-t, -k$column_index,$column_index"
  35. [ "$numeric_sort" = "numeric" ] && sort_options="$sort_options -n"
  36. # 执行排序并输出
  37. echo "$header"
  38. tail -n +2 "$input_file" | sort $sort_options