我的文本文件中有以下 2 行,并且想要计算这些行 X 和 Y 之间的持续时间(以分钟为单位)。
line X: 18.05.2022 13:54:52 [ INFO]: Starting Component 'OWN_FUNDS_RULES' (5/15)
line Y: 18.05.2022 14:28:22 [ INFO]: Finished Component 'OWN_FUNDS_RULES_CONSOLIDATION' (6/15) with SUCCESS - 00:07:05.119
我有以下代码,它将持续时间返回为零。
cd /logs/
Header="OFRComponentCalculation"
echo $Header >OutputFile.csv
for file in log_Job_*/process.log; do
### OFRComponentCalculation ###
{
OFRS="$(grep 'Starting Component*OWN_FUNDS_RULES*' "$file" | awk '{print $3,$4}' | cut -d: -f2-)"
OFRE="$(grep 'Finished Component*OWN_FUNDS_RULES_CONSOLIDATION*' "$file" | awk '{print $1,$2}' | cut -d: -f1-)"
convert_date() { printf '%s-%s-%s %s' ${1:6:4} ${1:3:2} ${1:0:2} ${1:11:8}; }
# Convert to timestamp
OFRS_TS=$(date -d "$(convert_date "$OFRS")" +%s)
OFRE_TS=$(date -d "$(convert_date "$OFRE")" +%s)
# Subtract
OFRD=$((OFRS_TS - OFRE_TS))
# convert to HH:MM:SS (note, that if it's more than one day, it will be wrong!)
OFRComponentCalculation=$(date -u -d "@$OFRD" +%H:%M:%S)
echo "$OFRComponentCalculation"
}
Var="$OFRComponentCalculation"
echo $Var >>OutputFile.csv
done
我怀疑在为这两行编写 grep 命令时弄乱了一些东西,任何人都可以帮助我。
答案1
这应该适合你:
:~$ cat event.log
18.05.2022 13:54:52 [ INFO]: Starting Component 'OWN_FUNDS_RULES' (5/15)
18.05.2022 14:28:22 [ INFO]: Finished Component 'OWN_FUNDS_RULES_CONSOLIDATION' (6/15) with SUCCESS - 00:07:05.119
:~$ cat calc_time.sh
#!/bin/bash
file="$1"
OFRS="$(grep "Starting Component 'OWN_FUNDS_RULES'" "$file" | cut -d ' ' -f1,2)"
OFRE="$(grep "Finished Component 'OWN_FUNDS_RULES_CONSOLIDATION'" "$file" | cut -d ' ' -f1,2)"
function date_time {
time_frame=$1
day=$(echo $time_frame | cut -d '.' -f1 )
month=$(echo $time_frame | cut -d '.' -f2 )
year=$(echo $time_frame | cut -d '.' -f3 | cut -d ' ' -f1)
hour=$(echo $time_frame | cut -d ' ' -f2 | cut -d ':' -f1)
minute=$(echo $time_frame | cut -d ' ' -f2 | cut -d ':' -f2)
second=$(echo $time_frame | cut -d ' ' -f2 | cut -d ':' -f3)
}
date_time "$OFRS"
sdate=$(date -d "$year"-"$month"-"$day"T"$hour":"$minute":"$second" +%s)
date_time "$OFRE"
fdate=$(date -d "$year"-"$month"-"$day"T"$hour":"$minute":"$second" +%s)
#Substraction
Exec_time=$(($fdate-$sdate))
echo Time of execution in seconds: $Exec_time
# convert to HH:MM:SS (note, that if it's more than one day, it will be wrong!)
OFRComponentCalculation=$(date -u -d "@$Exec_time" +%H:%M:%S)
echo "$OFRComponentCalculation"
然后您可以使用该文件作为参数来运行它:
:~$ bash calc_time.sh event.log
Time of execution in seconds: 2010
00:33:30