bash - 返回数组中最大值的索引 - bash
问题描述
给定一个输入格式为(经度、纬度、日期、时间、温度)的文件,编写一个 bash 脚本,返回列表中最高测量温度的位置和时间。
示例输入:
53.0382,96.5753,2010.11.16.,07:23,38
53.0382,96.5753,2000.06.21.,09:05,-16
53.0382,96.5753,2007.05.16.,02:00,-4
53.0382,96.5753,2008.07.27.,22:38,-6
53.0382,96.5753,2001.07.09.,09:50,-12
53.0382,96.5753,2016.12.08.,22:55,28
示例输出:
The highest measured temperature was 38 degrees on 2010.11.16. at 07:23. it was measured at the coordinates of 53.0382, 96.5753
我编写了一个脚本,该脚本成功地获取输入并将其拆分为不同的数组,用于给定的每个不同值。我试图循环遍历温度以找到最高温度的索引,使用它来索引输出的日期、时间和位置数组。
#!/bin/bash
latitude=(); longitude=(); date=(); time=(); value=();
while IFS=, read -ra arr;
do
latitude+=(${arr[0]})
longitude+=(${arr[1]})
date+=(${arr[2]})
time+=(${arr[3]})
value+=(${arr[4]})
done < temperatures.txt
max=0
maxI=0
count=$(wc -l <temperatures.txt)
for ((i=0; i<$count; i++)) ;
do
echo ${value[i]}
if ((${value[i]} > $max)) ; then
max=${value[i]}
maxI=$i
fi
done
echo $max
echo $maxI
使用上面的代码,我得到了错误syntax error: invalid arithmetic operator (error token is " > 0")
。第 17 行 if 语句似乎有问题。如果有人能对我的问题有所了解,我将不胜感激。
解决方案
跳过数组,只跟踪最高温度(和相关值),例如;
temp=-1000
while IFS=, read -r a b c d e
do
[[ "${e}" -gt "${temp}" ]] &&
long="${a}" &&
lat="${b}" &&
tdate="${c}" &&
ttime="${d}" &&
temp="${e}"
done < temperatures.txt
printf "The highest measured temperature was %s degrees on %s at %s. It was measured at the coordinates of %s, %s\n" "${temp}" "${tdate}" "${ttime}" "${long}" "${lat}"
这会产生:
The highest measured temperature was 38 degrees on 2010.11.16. at 07:23. It was measured at the coordinates of 53.0382, 96.5753
为了处理大量的行,我可能会选择类似的东西awk
(出于性能原因),例如:
awk -F, '
$5 > temp { long=$1; lat=$2; tdate=$3; ttime=$4; temp=$5 }
END { printf "The highest measured temperature was %s degrees on %s at %s. It was measured at the coordinates of %s, %s\n", temp, tdate, ttime, long, lat }
' temperatures.txt
推荐阅读
- laravel - 从 Laravel 刀片模板调用数据库
- django - 将 Django 的管理员用户连接到模型
- javascript - 为什么我的 React Router 在嵌套 Switch 中选择两个路由?
- c++ - 在 NVIDIA GEFORCE GTX 1050 上下载适用于 windows 10 的 openCL 1.2
- r - 如何将两个字符列转换为二进制矩阵?
- javascript - 获得滑动功能以替换下一个和上一个按钮
- python-3.x - Excel电子表格在word模板中生成文本
- ios - 如何在 SwiftUI 中位于 Apple Files App 的文件夹中写入文件?
- flutter - Flutter:多个小部件使用相同的 GlobalKey
- r - 如何在 R 中的 x 上绘制日期时间?