我尝试通过运行sed命令来过滤系统日志 像:
error
info_a1
info_a2
info_a3
crit
info_b
error
info_c1
info_c2
warn
info_d
error
info_x
error
info_p
info
info_w
error
info_z1
info_z2
我希望得到所有错误消息,如:
error
info_a1
info_a2
info_a3
error
info_c1
info_c2
error
info_x
error
info_p
error
info_z1
info_z2
我用
sed -n" / error /,/ [info | warn | crit |] / p"
但它不能很好地工作。
答案 0 :(得分:3)
awk '
/^error/ {p=1}
/^(info|warn|crit)/ {p=0}
p
'
答案 1 :(得分:1)
如果您的目标是打印错误消息及其后的下一行,请使用
cat file_name | grep 'error' -A 1 | grep -v '\-\-'
答案 2 :(得分:0)
如果您只想让所有行中出现“错误”,
grep "error" file
如果你坚持使用sed
sed -n '/error/p' file
甚至是awk
awk '/error/' file
或Ruby
ruby -ne 'print if /error' file
答案 3 :(得分:0)
这是sed
版本:
sed -n ':a;/^error/{h;:b;n;${/^[[:blank:]]/{H;x;/^error/{p;q}}};/^[^[:blank:]]/{x;p;x;ba};H;bb}' inputfile
说明:
:a # label a
/^error/{ # if pattern space (patt) begins with "error"
h # copy the line to hold space (hold)
:b # label b
n # read the next line
${ # if it's the last line of input
/^[[:blank:]]/{ # if it begins with a space, tab, etc.
H # append it to hold
x # exchange patt and hold
/^error/{ # if patt begins with "error"
p # print it
q # quit
}
}
}
/^[^[:blank:]]/{ # if patt starts with a non-blank (a new block of input has started
x # exchange patt and hold
p # print patt
x # exchange patt and hold
ba # branch to label a
}
H # append patt to hold (save a line of the current block)
bb # branch to b
}