如何在shell脚本中提取结构化文件的单个字段按指定格式输出
问题原因与解决方案
核心错误点
- 字段分隔符配置错误:源文件字段以分号
;分隔,但你的cut命令用-d:指定了冒号作为分隔符,无法正确切割字段,因此每次返回整行内容。 - 遍历逻辑效率低下:逐行调用
head | tail读取文件,文件体积较大时会产生严重的性能损耗。 - 未跳过表头行:源文件第一行是字段名定义,直接遍历会把表头当成有效车辆数据输出。
修改后的可用脚本
推荐使用read直接按分隔符读取字段,逻辑更简洁性能更高:
#!/bin/bash # 跳过第一行表头,按分号分隔读取所有字段 tail -n +2 cars2.csv | while IFS=";" read -r car mpg cylinders displacement horsepower weight acceleration model origin do # 自动去除字段前后的多余空格(匹配你源文件的格式问题) car=$(echo "$car" | xargs) origin=$(echo "$origin" | xargs) # 按要求格式输出 echo "Car: $car" echo "MPG: $mpg" echo "Cylinders: $cylinders" echo "Displacement: $displacement" echo "Horsepower: $horsepower" echo "Weight: $weight" echo "Acceleration: $acceleration" echo "Model: $model" echo "Origin: $origin" # 不同车辆输出之间加空行分隔 echo "" done
保留原有循环逻辑的修改方案
只需要修正两个点即可正常运行:
- 把
cut的分隔符从:改成; - 跳过i=1的表头行
修改后的循环内代码示例:
# 跳过第一行表头 if [ $i -gt 1 ];then name=`head -$i cars2.csv | tail -1 | cut -d';' -f1 | xargs` mpg=`head -$i cars2.csv | tail -1 | cut -d';' -f2` echo "Car: $name" echo "MPG: $mpg " # 其余字段按相同规则取f3到f9即可 fi
内容的提问来源于stack exchange,提问作者AnonymousDeveloper
相关产品推荐
相关产品推荐

