簡體   English   中英

如何使用正則表達式模式格式化grep的輸出以在字符串和字符之間進行匹配

[英]How to format the output of a grep with a regex pattern to match between a string and character

我一直在研究bash腳本,該腳本可以將字符串從logFile出現到outputFile中以監視其頻率。 我想進一步過濾並使用該grep的結果,然后將字符串的一部分格式化為我的最終結果。

目前,我的grep如下獲取我需要的logFile輸出部分:

grep -n -A 1 "No entry for this particular code type" logFile.txt >> outputfile.txt

這將獲得以該字符串開頭的完整行,如下所示,代碼類型的值在整個日志中不斷變化:“此特定代碼類型無條目,代碼類型:001123。” 等等

我想解析從grep輸出的上述結果行,只檢索字符串“代碼類型:”和字符“。”之間的值。 這會給我類似001123的值

我一直在網上尋找解決方案,但沒有嘗試過。 任何建議將不勝感激。

您可以使用sed通過另一個正則表達式提取數字:

cat outputfile.txt | sed 's/.*code type: \(.*\)\./\1/'

\\1引用表達式(第一個匹配組 )的\\(.*\\)部分的內容。

您可以使用bash內置的regEx支持來實現。 假設您將輸出捕獲在bash變量中

$ myString="No entry for this particular code type, code type: 001123."
$ [[ $myString =~ code\ type:(.*). ]] && subString="${BASH_REMATCH[1]}"
$
$ printf "%s\n" "$subString"
001123

(或)如果可以再次使用通過管道傳遞的grep進行regEx捕獲,請執行

$ <first_grep_command> | grep -Po "code type: \K.*(?=.)"
001123

其中-P標志僅支持perl樣式正則表達式匹配,而-o標志僅返回匹配的字符串。

這直接在我的外殼中工作:

echo "No entry for this particular code type, code type: 001123." |grep -Po '[0-9]*'

意思是說,這種方法可以在沒有太多管道的情況下適用於您的情況:

grep -Po '[0-9]*' logfile.txt >>outputfile.txt

暫無
暫無

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

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