如何编写可复用Shell脚本获取CSV中各房间最高温度(不使用awk)
问题
现有包含Time、Room no、Temperature value字段的CSV输入文件,需要编写不使用awk的Shell脚本,输出每个房间的最高温度。目前已实现固定5个房间的代码,但无法适配任意数量(N个)房间,希望实现代码可复用。已尝试的代码如下:
max_val1=0 max_val2=0 max_val3=0 max_val4=0 max_val5=0 #Using loop to read the file and save it as column while IFS=, read -r Time Room Value do if [ $Room == "Room1" ] #Comparing then if [ $Value -gt $max_val1 ]; then max_val1=$Value fi fi if [ $Room == "Room2" ] then if [ $Value -gt $max_val2 ]; then max_val2=$Value fi fi if [ $Room == "Room3" ] then if [ $Value -gt $max_val3 ]; then max_val3=$Value fi fi if [ $Room == "Room4" ] then if [ $Value -gt $max_val4 ]; then max_val4=$Value fi fi if [ $Room == "Room5" ] then if [ $Value -gt $max_val5 ]; then max_val5=$Value fi fi done< <(tail -n+2 data.csv) echo "Room 1 ,"$max_val1 echo "Room 2 ,"$max_val2 echo "Room 3 ,"$max_val3 echo "Room 4 ,"$max_val4 echo "Room 5 ,"$max_val5
解决方案
使用Bash的关联数组可以动态存储任意数量房间的最高温度,无需预先定义固定变量。改进后的脚本如下:
#!/bin/bash # 初始化关联数组,键为房间名称,值为对应最高温度 declare -A max_temps # 跳过表头,逐行读取CSV内容 tail -n+2 data.csv | while IFS=, read -r Time Room Value; do # 跳过非数值的温度值(可选,根据实际数据调整) if ! [[ "$Value" =~ ^[0-9]+(\.[0-9]+)?$ ]]; then continue fi # 若房间无记录,直接赋值当前温度为初始最大值 if [[ -z "${max_temps[$Room]}" ]]; then max_temps[$Room]="$Value" else # 浮点数值比较用bc,整数可改用[ $Value -gt ${max_temps[$Room]} ] if (( $(echo "$Value > ${max_temps[$Room]}" | bc -l) )); then max_temps[$Room]="$Value" fi fi done # 遍历关联数组,输出每个房间的最高温度 for room in "${!max_temps[@]}"; do echo "$room,${max_temps[$room]}" done
核心要点
declare -A max_temps:声明关联数组,自动适配任意数量的房间,无需提前定义变量。- 浮点温度处理:用
bc -l完成浮点数值比较,若数据仅为整数,可简化为整数比较逻辑。 - 数据校验:增加非数值跳过逻辑,避免异常数据导致脚本报错,可根据实际情况移除。
内容的提问来源于stack exchange,提问作者Ram Prasad
相关产品推荐
相关产品推荐

