| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- #!/bin/bash
- # 输入检查
- if [ $# -lt 2 ]; then
- echo "用法: $0 <CSV文件> <排序列名> [numeric]"
- echo "示例: $0 data.csv Age numeric"
- exit 1
- fi
- input_file="$1"
- sort_column="$2"
- numeric_sort="${3:-text}"
- # 检查文件是否存在
- if [ ! -f "$input_file" ]; then
- echo "错误: 文件 '$input_file' 未找到"
- exit 1
- fi
- # 提取标题行
- header=$(head -n 1 "$input_file")
- # 确定列索引
- column_index=$(echo "$header" | awk -F, -v col="$sort_column" '{
- for(i=1; i<=NF; i++) {
- if ($i == col) {
- print i
- exit
- }
- }
- print -1
- }')
- # 列名检查
- if [ "$column_index" -eq -1 ]; then
- echo "错误: 列 '$sort_column' 在标题中未找到"
- exit 1
- fi
- # 设置排序参数
- sort_options="-t, -k$column_index,$column_index"
- [ "$numeric_sort" = "numeric" ] && sort_options="$sort_options -n"
- # 执行排序并输出
- echo "$header"
- tail -n +2 "$input_file" | sort $sort_options
|