无法连接bash变量

问题描述 投票:1回答:1

我收集了数据(5000行CSV数据),我想制作一个图表,但是有一个问题。在我的匆忙和兴奋中,我忘记了数据收集何时开始。 Arduino程序测量温度和光照水平(一分钟内更多),每秒一次,并在该观察上标记相对时间戳。时间戳是自程序启动以来的毫秒数。幸运的是,由于文件上的Linux时间戳,我也知道程序结束的时间。因此,从结束时间开始向后工作,我能够获得开始时间。

这是开始数据:(使用head命令)

10510707,PV1,1,753.00,PV2,2,129.00,TS1,5,114.13,TS2,7,97.70,WWVB,0,213.00
10512621,PV1,1,753.00,PV2,2,130.00,TS1,5,114.57,TS2,7,97.70,WWVB,0,212.00
10514536,PV1,1,752.00,PV2,2,128.00,TS1,5,114.69,TS2,7,97.70,WWVB,0,212.00
10516450,PV1,1,752.00,PV2,2,129.00,TS1,5,114.80,TS2,7,97.70,WWVB,0,211.00

这是结束数据(使用tail命令)

20067422,PV1,1,700.00,PV2,2,89.00,TS1,5,117.39,TS2,7,96.80,WWVB,0,198.00
20069336,PV1,1,700.00,PV2,2,90.00,TS1,5,116.94,TS2,7,96.80,WWVB,0,198.00
20071248,PV1,1,700.00,PV2,2,90.00,TS1,5,116.94,TS2,7,96.80,WWVB,0,198.00
20073161,PV1,1,700.00,PV2,2,90.00,TS1,5,116.94,TS2,7,96.80,WWVB,0,198.00

根据我的计算,第一行的时间戳应为:

Mon Aug 21 13:04:42 EDT 2017,10510707,PV1,1,753.00,PV2,2,129.00,TS1,5,114.13,TS2,7,97.70,WWVB,0,213.00

并且最后一行的时间戳应为:

Mon Aug 21 15:44:04 EDT 2017,20073161,PV1,1,700.00,PV2,2,90.00,TS1,5,116.94,TS2,7,96.80,WWVB,0,198.00

听到的是我正在处理的剧本:

#!/bin/bash
while IFS='' read -r line || [[ -n "$line" ]]; do

#step 1. Get the very first millisecond value in a variable
VarFirstMilliSeconds=$ cat newberry_subset.csv | awk -F, '{print $1}'

#Subsequent Milliseconds
VarMilliSeconds=$(echo "$line" |cut -d "," -f 1)

#declaration of 1 second
declare -i x=1000

#August 21 2017 converted into epoch date
VarFirstDate=$(date -j -f "%d-%B-%y" 21-AUG-17 +%s)

# First millisecond time - current milliseconds
VarDifferenceOfMilliSeconds=$(expr "$VarFirstMilliSeconds"-"$VarMilliSeconds")


# Calculated difference of first milliseconds and current milliseconds divide 
by 1000
# to get seconds to add to epoch date
VarDifferenceOfSeconds=$(expr "$VarDifferenceOfMilliSeconds"/"$x")


# epoch date with difference of first date and current milliseconds added
NewEpochDate=$(expr "$VarFirstDate"+"$VarDifferenceOfSeconds")

# converted epoch date to human readable format
ConvertedEpochDate=$(echo "$NewEpochDate" | awk '{ print strftime("%c", $1); 
}')

LineWithOutMili=$(echo "$line" | cut -d "," -f 2-16)

ConvertedEpochTime=$(echo "$ConvertedEpochDate" | cut -d " " -f 4 | cut -d ":" 
-f 1-2)

echo "$ConvertedEpochTime,$LineWithOutMili"


done < "$1"

问题是我运行脚本它没有连接变量,生成一个csv需要很长时间

linux bash csv awk
1个回答
3
投票

您可以在单个Awk命令中完成所有操作。除了修复原始bash脚本中的几个语法问题。

作为第一步,在shell变量中获取EPOCH中的原始时间,然后在Awk中使用它来进行第一个字段的后续转换。我已经使用了FreeBSD命令的date版本,看到你使用了同样的版本。

origin=$(date -j -f "%a %b %d %T %Z %Y" "Mon Aug 21 13:04:42 EDT 2017" +%s)

现在我们将使用origin变量并执行所需的计算

awk -v start="$origin" 'BEGIN{FS=OFS=","}{delta=sprintf("%.0f", (start - ($1/1000))); $1=strftime("%a %b %e %H:%M:%S %Z %Y",delta)}1' csv_file

或者,如果要将时间戳包含为新列,并且还包含所有先前的列

awk -v start="$origin" 'BEGIN{FS=OFS=","}{delta=sprintf("%.0f", (start - ($1/1000))); print strftime("%a %b %e %H:%M:%S %Z %Y",delta),$0}' csv_file
© www.soinside.com 2019 - 2024. All rights reserved.