awk 'tolower($0) ~ /\.[log(message|event)|trace(error)?c?|infoc?|warnc?|debugc?|errorc?]/,/)/{gsub(/^\t /, "", $0);print NR","$0}' example_file
我創建了這個腳本,它在檔案中查找模式,例如:
log.Info("hello world")
log.Error()
并輸出類似:
4,log.Info("hello world")
7,log.Error()
行號和文本本身。
問題是,如果我的檔案中有這樣的內容:
log.Info("hello world")
log.Warn(
"hello world")
log.Error()
它將輸出如下內容:
4,log.Info("hello world")
5,log.Warn(
6,"hello world")
7,log.Error()
我想制作"hello world")與log.Warn(.
就像如果找到的下一行不是以模式開頭,/\.[log(message|event)|trace(error)?c?|infoc?|warnc?|debugc?|errorc?]/它會將這一行放在之前的行上。
所需的輸出類似于:
4,log.Info("hello world")
5,log.Warn("hello world")
7,log.Error()
非常感謝你。
uj5u.com熱心網友回復:
就像如果找到的下一行不是以模式 /.[log(message|event)|trace(error)?c?|infoc?|warnc?|debugc?|errorc?]/ 開頭,它會將這一行放在在那之前的那條線。
不能根據下一行進行操作,只能根據當前行進行操作。這基本上意味著您必須:
- 緩沖一行(前一行)
- 如果當前行確實以模式 /.[log(message|event)|trace(error)?c?|infoc?|warnc?|debugc?|errorc?]/ 開頭,則輸出上一行。上一行成為當前行。
- 否則,輸出上一行和當前行。上一行變為空。
- END { 輸出上一行 }
一些東西:
awk '
/^log\./{ # the pattern here
if (last) {
print NR - 1, last; # output previous line
}
last=$0 # previous line becomes current line
next
}
{ # otherwise, because next above
print NR - 1, last $0 # output previous line and current line
last="" # previous line becomes empty.
}
END{
if (last) {
print NR, last # Handle previous line on the end.
}
}
'
改變你的條件,所以它只取決于“當前行”。例如,如果當前行不以 結尾),則吃下一行。
awk '/[^)]$/{
n=NR
a=$0
getline
print n " " a $0
}'
uj5u.com熱心網友回復:
這是一個盡力而為的腳本(即會在各種下雨天的情況下失敗),使用此輸入檔案:
$ cat file
foo
log.Info("hello
world")
log.Warn(
"hello
some other
world")
log.Error()
bar
和任何 POSIX awk:
$ cat tst.awk
BEGIN {
begRe = "log[.](Info|Warn|Error)[(]"
regexp = begRe "[^)]*[)]"
OFS = ","
}
$0 ~ begRe {
begNr = NR
buf = ""
}
begNr {
buf = buf $0
if ( match(buf,regexp) ) {
buf = substr(buf,RSTART,RLENGTH)
gsub(/[[:space:]]*"[[:space:]]*/,"\"",buf)
print begNr, buf
begNr = 0
}
}
$ awk -f tst.awk file
2,log.Info("hello world")
4,log.Warn("hello some other world")
8,log.Error()
如果您想折疊引號內的所有空格并洗掉任何前導空格,則只需gsub(/[[:space:]] /," ",buf); gsub(/^ | $/,"",buf)在列印陳述句之前添加。
$ cat tst.awk
BEGIN {
begRe = "log[.](Info|Warn|Error)[(]"
regexp = begRe "[^)]*[)]"
OFS = ","
}
$0 ~ begRe {
begNr = NR
buf = ""
}
begNr {
buf = buf $0
if ( match(buf,regexp) ) {
buf = substr(buf,RSTART,RLENGTH)
gsub(/[[:space:]]*"[[:space:]]*/,"\"",buf)
gsub(/[[:space:]] /," ",buf); gsub(/^ | $/,"",buf)
print begNr, buf
begNr = 0
}
}
$ awk -f tst.awk file
2,log.Info("hello world")
4,log.Warn("hello some other world")
8,log.Error()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378747.html
