How do I print a line which matches a particular pattern and the line before it?
I do have a dump like this:
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;
The output result to be the above line of "Fault Code 9" with Fault Code 9 included:
Apple:Orange=9942501133;
Fault Code 9
Apple:Orange=9942501144;
Fault Code 9
Apple:Orange=9942501177;
Fault Code 9
Apple:Orange=9942501211;
Fault Code 9
# grep -B1 ^Fault log.txt
The -B
switch means "before".
This should do the job.
cat yourfile | perl -e 'while(<STDIN>) { if(/Fault Code 9/) { print $prev; } $prev=$_; }'
In pure shell:
cat yourfile | while read line
do
if [ "$line" == "Fault Code 9" ]; then
echo "$prev"
fi
prev=$line
done
gawk:
/^Fault Code 9/ {
print s
print $0
}
{
s = $0
}
grep -B1 'Fault Code 9' filename.txt
tr -d '\n' <yourfile | grep -E -o '[^; ]+; *Fault Code 9' | sed 's/;.*$//'
精彩评论