
我有以下類型的文字文件,
a b c d
-- -- -- --
1 ok device issue Some Action which
has to be taken which
is split into many lines
under d.
我嘗試使用 grep 來表示“問題”,但是只列印了“d”的第一行。我得到的輸出是:
1 ok device issue Some Action which
不過我想要 d 中的完整輸出。當我嘗試將檔案儲存為 csv 時,它顯示 d 列的第二行作為新行。
編輯:
輸出是從多個設備獲得的,這些設備儲存在一個變數中,我從中尋找有問題的設備。
答案1
這裡需要多行 grep。為此,我們需要啟用 PCRE-P
選項。由於 grep 將在 slurp-z
模式下輸出 Null 分隔記錄,因此我們透過 tr 指令刪除這些記錄。
$ < file grep -Pzo '.*\S.*issue.*\n(?:\h+.*\n)+' | tr -d '\0'
答案2
grep
表現得像預設模式下應該的那樣。從其man
頁面:
...grep 在每個文件中搜尋模式。 PATTERNS 是一個或多個由換行符號分隔的模式,grep 列印與模式相符的每一行...
所以,它應該會出現線在符合 a 的文字中regex
。線條由控製程式碼劃分newline
,這解釋了您所看到的行為。除了使用-z
回復中提到的選項之外。假設“issue”是您想要匹配的正規表示式(如果您實際上想要匹配,請替換為'Device Degraded'
or'\sDegraded'
或);'\sError'
並且「糾正措施」列是機器生成的並且一致,即始終跨越 4 行,您也可以簡單地運行grep -A 3 '\sissue' > issues
來保存僅您感興趣的線路到一個文件中。您必須能夠產生如下所示的輸出:
1 ok device issue Some Action which
has to be taken which
is split into many lines
under d.
--
10 ok device issue Some Action which
has to be taken which
is split into may lines
under d.
--
211 ok device issue Some Action which
has to be taken which
is split into many lines
under d.
檢查 grep 的手冊頁以了解有關這些選項的更多資訊。
答案3
假設輸入檔中的「記錄」與OP提供的完全相同:
$ sed '/issue/!d; :a; n; /^[0-9]\{1,\} /d; $!ba' file
1 ok device issue Some Action which
has to be taken which
is split into many lines
under d.
$
答案4
這可能就是您想要的,在每個 UNIX 機器上的任何 shell 中使用任何 awk:
$ cat tst.awk
/^[0-9]/ { prt() }
{ rec = rec $0 ORS }
END { prt() }
function prt() {
if ( rec ~ regexp ) {
printf "%s", rec
}
rec = ""
}
。
$ awk -v regexp='issue' -f tst.awk file
1 ok device issue Some Action which
has to be taken which
is split into many lines
under d.