Bash
使用 grep 從文本文件中提取帶有表達式的文本
我的文本文件中有以下兩行,並希望以分鐘為單位計算這些行 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
我懷疑在為這 2 行編寫 grep commangs 時搞砸了一些東西,任何人都可以幫助我。
這應該為你做:
:~$ 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