簡體   English   中英

編寫 bash sed 命令時遇到問題 - 正則表達式匹配

[英]Trouble writing bash sed command - regex match

我有一個充滿不規則垃圾收集信息的文件,有些行有我想最初刪除的額外信息,以便我可以將文件作為一個整體進行處理。

不幸的是,該行有很多特殊字符,我正在努力使用 sed 命令,該命令設法匹配我想要刪除的位...

該行包括以下內容:

[ParOldGen: 0K->0K(0K)] 0K->0K(0K), [Metaspace: 0K->0K(0K)], 0 secs]

該行有關於我確實想保留的上述字符串的其他信息,包括[]()字符。

我要搭配

[ParOldGen*secs]

然后使用 sed 刪除它

cat test.log | sed -e 's,<match>,,g' | ...

我去檢查了一個正則表達式檢查器,它想出了:

\[ParOldGen(?:(?!secs\])(?:.|\n))*secs\]

但是,它與 sed -e 不匹配,並且在使用 sed -E 時出錯

我不能輕易使用 cut 因為有太多其他部分有 [ 和 ]。

我正在嘗試這樣的事情:

cat test.log | while read line; do if [ "$line" == *"ParOldGen"* ];then cut -d ":" -f 1,9; else cut -d ":" -f 1,7; fi; done | tail

這將有效地解決它,但我無法在 ParOldGen 上獲得匹配,它總是只執行 then 部分。

我的預期輸出是我想刪除 ParOldGen 行。

有人能幫我解決這個問題嗎?

謝謝!

我正在假設您要從文件的每一行中刪除以[ParOldGen開始並以secs]的整個字符串。 在這種情況下,您可以使用以下sed命令:

sed -e 's/^\(.*\)\[ParOldGen.*secs\]\(.*\)$/\1\2/' test.log

正則表達式將[ParOldGen之前的任何字符[ParOldGen到一個捕獲組中,並將secs]之后的任何字符[ParOldGen到另一個捕獲組中。 然后整行被這兩個捕獲組替換,有效地從[ParOldGensecs]刪除字符。 例如,如果 test.log 包含:

[Some other data (4) ][ParOldGen: 0K->0K(0K)] 0K->0K(0K), [Metaspace: 0K->0K(0K)], 0 secs] and then some more [possibly also with ()]

cat test.log | sed -e 's/^\\(.*\\)\\[ParOldGen.*secs\\]\\(.*\\)$/\\1\\2/'的輸出cat test.log | sed -e 's/^\\(.*\\)\\[ParOldGen.*secs\\]\\(.*\\)$/\\1\\2/' cat test.log | sed -e 's/^\\(.*\\)\\[ParOldGen.*secs\\]\\(.*\\)$/\\1\\2/'

[Some other data (4) ] and then some more [possibly also with ()]

暫無
暫無

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

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