Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the line before pattern that won't match pattern

I have a file with the following lines

4278.82888126 , 17 , 17 , 0
4289.29672647 , Marker 1
4478.07865548 , 18 , 18 , 0
5289.84818625 , 19 , 19 , 0
5377.07618618 , Marker 2
5505.54010463 , 20 , 20 , 0
5869.55748796 , 21 , 20 , 1
6057.54284048 , 22 , 20 , 2
6161.77394795 , 23 , 20 , 3
6455.30569553 , Marker 3
7594.11082244 , Marker 4

For every Marker, I need a valid line (not a Marker line) that is right before it. I tried with

grep -B1 "Marker" file | grep -v Marker | grep -v '\-\-'

But that did not give me a line for every marker. It seems to be an easy one but how do I get the following lines?

 4278.82888126 , 17 , 17 , 0
 5289.84818625 , 19 , 19 , 0
 6161.77394795 , 23 , 20 , 3
 6161.77394795 , 23 , 20 , 3
like image 581
reencode Avatar asked Dec 06 '25 17:12

reencode


1 Answers

Just store lines in a variable and if the line containing marker is found, print the variable.

$ awk '/Marker/ && line { print line; next } { line = $0 }' file
4278.82888126 , 17 , 17 , 0
5289.84818625 , 19 , 19 , 0
6161.77394795 , 23 , 20 , 3
6161.77394795 , 23 , 20 , 3
  • /Marker/ && line is an action which tests if the line contains Marker and if the variable line is set. If it is then it prints the variable.
  • next allows us to move to the next line so we don't end up storing the current line containing Marker in our variable.
  • For all lines that do not contain Marker we keep storing in a scalar variable to be printed later on.
like image 65
jaypal singh Avatar answered Dec 08 '25 08:12

jaypal singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!