开发者

Prior line should be printed if the next line starts with a particular word

开发者 https://www.devze.com 2023-01-07 14:52 出处:网络
How do I print a line which matches a particular pattern and the line before it? I do have a dump like this:

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/;.*$//'
0

精彩评论

暂无评论...
验证码 换一张
取 消