【发布时间】:2015-08-07 21:26:48
【问题描述】:
我正在构建一个脚本,该脚本读取每天 24 小时的温度数据,以提取较小域的经纬度区域。每个数据文件有温度-经度-纬度三列,188426行。
> ==> 20120810234500.txt <==
> 0.0362,-12.5000,33.5000
> -0.0188,-12.5000,33.5400
> -0.0732,-12.5000,33.5800
> -0.1263,-12.5000,33.6200
> -0.1778,-12.5000,33.6600
> -0.2278,-12.5000,33.7000
> -0.2761,-12.5000,33.7400
> -0.3226,-12.5000,33.7800
> -0.3677,-12.5000,33.8200
> -0.4115,-12.5000,33.8600
我使用 for 和 while 循环和 awk 命令来读取数据,但读取、提取和抓取新的较小文件需要很长时间(至少对我而言)。在这里可以看到脚本的相关部分
# Start 24 hours loop
lom1=-3
lom2=3
lam1=35
lam2=42
nhoras=24
n=1
while [ $n -le $nhoras ]
do
# File name (nom_file) and length (nstation=188426)
nom_file=`awk -v i=$n 'BEGIN { FS = ","} NR==i { print $1 }' lista_datos.txt`
nstation=`awk 'END{print NR}' $nom_file`
# Original data came from windows system and has carriage returns
dos2unix -q $nom_file
# Date, time values from file name
year=`echo $nom_file | cut -c 1-4`
month=`echo $nom_file | cut -c 5-6`
day=`echo $nom_file | cut -c 7-8`
hour=`echo $nom_file | cut -c 9-14`
# Part of the string to write in the new smaller file
var1=`echo $nom_file | awk '{print substr($0,1,4) " " substr($0,5,2) " " substr($0,7,2) " " substr($0,9,6)}'`
# Read rows 65000 to 125000 to gain processing time
m=65000
#while [ $m -le $nstation ] # Bucle extración datos
while [ $m -le 125000 ] # Bucle extración datos
do
station_id=$m
elevation=1.5
lat=`awk -v i=$m 'BEGIN { FS = ","} NR==i { print $3 }' $nom_file`
lon=`awk -v i=$m 'BEGIN { FS = ","} NR==i { print $2 }' $nom_file`
# As lon/lat are floating point I use this workaround to get a smaller region
lom1=`echo $lon'>'$lon1 | bc -l`
lom2=`echo $lon'<'$lon2 | bc -l`
lam1=`echo $lat'>'$lat1 | bc -l`
lam2=`echo $lat'<'$lat2 | bc -l`
if [ $lom1 -eq 1 ] && [ $lom2 -eq 1 ];
then
if [ $lam1 -eq 1 ] && [ $lam2 -eq 1 ];
then
# Second part of the string to write in the new smaller file
var2=`awk -v i=$m -v e=$elevation 'BEGIN { FS = ","} NR==i { print "'${station_id}' " $3 " " $2 " '${elevation}' 000 " $1 " 000" }' $nom_file`
# Paste
paste <(echo "$var1") <(echo "$var2") -d ' ' >> out.txt
fi # final condición lat
fi # final condición lon
m=$(( $m + 1 ))
done # End of extracting loop
# Save results
cat cabecera-dp-s.txt out.txt > dp-s$year-$month-$day-$hour
rm out.txt
n=$(( $n + 1 ))
done # End 24 hours loop
现在处理一个输入文件需要两个小时。有什么办法可以加快这个过程吗?
提前致谢
【问题讨论】:
-
看起来您在阅读完整文件时多次致电
awk。在awk中完成所有流程怎么样?我没有深入研究逻辑,但如果你给出一个模式,以及一个基本的示例输入/所需的输出,它会更容易为你提供帮助。 -
或换一种说法:当您将结果分配给变量的命令输出时,您每次调用 awk 或 cut 或创建子进程的任何命令。示例:如果您的代码每次运行创建 30 个子进程,并且您针对 3000 个文件运行它,则必须创建 90000 个子进程。这是很多开销。每次运行您都会创建超过 30 个子进程。
-
太疯狂了,您正在读取整个文件 60,000 次两次(一次是从同一行获取字段 2,另一次是从同一行获取字段 3!),每个小时从头到尾完整地读取一次,即 24次!以
lat=...和lon=...开头的行太疯狂了! -
查看
read内置和bash的参数扩展运算符,特别是子字符串扩展(例如,foo=abcde,${foo:2:2}将是字符串“cd”) . -
查看mywiki.wooledge.org/BashFAQ/001 了解如何在
bash中逐行读取文件。