如何打印与特定图案和之前的线匹配的线?
我确实有这样的转储:
Apple:Orange=9942501133;
Fault Code 9
Apple:Orange=9942501144;
Fault Code 9
Apple:Orange=9942501155;
Apple:Orange=9942501166;
Apple:Orange=9942501177;
Fault Code 9
Apple:Orange=9942501188;
Apple:Orange=9942501199;
Apple:Orange=9942501200;
Apple:Orange=9942501211;
Fault Code 9
Apple:Orange=9942501222;
输出结果为“故障代码9”的上述行,其中包含故障代码9:
Apple:Orange=9942501133;
Fault Code 9
Apple:Orange=9942501144;
Fault Code 9
Apple:Orange=9942501177;
Fault Code 9
Apple:Orange=9942501211;
Fault Code 9
答案 0 :(得分:3)
# grep -B1 ^Fault log.txt
-B
开关的意思是“之前”。
答案 1 :(得分:1)
这应该可以胜任。
cat yourfile | perl -e 'while(<STDIN>) { if(/Fault Code 9/) { print $prev; } $prev=$_; }'
在纯shell中:
cat yourfile | while read line
do
if [ "$line" == "Fault Code 9" ]; then
echo "$prev"
fi
prev=$line
done
答案 2 :(得分:1)
GAWK:
/^Fault Code 9/ {
print s
print $0
}
{
s = $0
}
答案 3 :(得分:0)
tr -d '\n' <yourfile | grep -E -o '[^; ]+; *Fault Code 9' | sed 's/;.*$//'
答案 4 :(得分:0)
grep -B1 'Fault Code 9' filename.txt