簡體   English   中英

使用grep將bash變量匹配為數字文字

[英]Matching bash variables as number literals with grep

我有一個(GNU)bash腳本,該腳本建立了兩個要在文件中匹配的變量。

hour=$(head -n 1 sensorstest.log | cut -f5 | cut -d"-" -f1)
dom=$(head -n 1 sensorstest.log | cut -f5 | cut -d"-" -f4)

...並將其與文件中的其他匹配項

grep -E [^0-9]+"$hour"-[0-9]+-[0-9]+-"$dom"-[0-9]+-[0-9]{4} sensorstest.log

這是一個腳本示例,用於計算一天中給定時間的輸入文件字段2中所有值的平均值。

hMean=$(grep -E [^0-9]+"$hour"-[0-9]+-[0-9]+-"$dom"-[0-9]+-[0-9]{4} sensorstest.log | cut -f2 | awk ' {sum+=$
1}{count++}{mean=sum/count} END {printf("%.2f",mean) } ' );

這是清除輸入文件的示例。

echo "removing: "$hour"th hour of the "$dom"th day  of the "$month"th month"
sed -i -r '/'"$hour"'-[0-9]+-[0-9]+-'"$dom"'-'"$month"'-[0-9]{4}/d' sensorstest.log

最后...這是文件中的示例行:

格式為:

OK 94.4 16.9 1443058486 1-34-46-24-9-2015

on the of the first entry in the file. 我正在嘗試匹配文件中第一個條目的所有實例。

對於9以下的數字,此方法工作正常。

問題:超過9的數字被匹配為兩個個位數,導致12個匹配的1,2,12,21 ...等。

這是旅行的一個例子:

OK 100 17.2 1442570381 2015年9月59日-41-18-9-

OK 100 17.1 1442570397 9-59-57-18-9-2015

保濕100 17.6 1442574014 11-0-14-18-9-2015

保濕100 17.6 1442574030 11-0-30-18-9-2015

在這里,輸出跳至0-0-0-19-9-2015(是的,我從日志中丟失了一個小時的條目)

$ sudo statanhourtest.sh

100,1.4,1.40,-98.6      16.5,17.2,16.90,.7      1442566811      9-0-0-18-9-2015

removing: 9th hour of the 18th day  of the 9th month
$ sudo statanhourtest.sh

100,1.4,1.40,-98.6      18.3,18.8,18.57,.5      1442620804      0-0-0-19-9-2015

removing: 0th hour of the 19th day  of the 9th month

問題僅在幾個小時內發生。 當天($dom)匹配良好。

option with grep, but I think this only returns the exact match where I need the whole line. 我已經嘗試在grep中使用選項,但是我認為這只會返回我需要整行的完全匹配項。

在線上關於grep中的數字匹配的信息並不多。 而且我沒有發現將bash變量用作數字文字。

任何幫助或相關鏈接將不勝感激。

編輯:經過一整夜的腳本挖掘后,我已經解決了問題。 expression right at the end. 問題出在我最后的表達上。 問題在於sed表達式的單引號部分和shell擴展的雙引號變量。 我是從另一個線程的建議中得出的。 雙引號整個表達式解決了這個問題。

suggestion has greatly increased the efficiency and accuracy of the script. 建議極大地提高了腳本的效率和准確性。 再次感謝。

敬請解救!

我認為您可以將所有內容組合到一個簡單的awk腳本中,而無需任何正則表達式。 例如,

awk 'NR==1{split($NF,h,"-")} {split($NF,t,"-")} t[1]==h[1] && t[4]==h[4]'

將解析文件第一行上的時間戳,僅過濾小時和日期匹配的記錄。

這將取字段2的平均值

awk 'NR==1
     {
          split($NF,h,"-")
     } 
     {             
          split($NF,t,"-")
     } 
     t[1]==h[1] && t[4]==h[4]
     {
          sum+=$2;
          c++
     } 
     END 
     {
          print "Average: " sum/c
     }'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM