Get a string in front of a pattern that won't match a 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 each marker, I need a valid line (not the marker line) that is right before it. I tried with

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

      

But that didn't give me a line for each marker. It seems to be simple, 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

      

+3


source to share


2 answers


Just store the lines in a variable and, if a line containing the 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 that checks if a string contains Marker

    and if a variable is set line

    . If it is, then it prints the variable.
  • next

    lets go to the next line so that we don't save the current line containing Marker

    in our variable.
  • For all lines that do not contain Marker

    , we store the save in a scalar variable that will be printed later.
+6


source


Using python, its simple:



>>> import re
>>> f = open('ll.txt')
>>> prev = f.next().strip()
>>> for x in f:
...     if re.search('Marker',x) and not re.search('Marker',prev):
...         print prev
...     else: prev = x.strip()
... 
4278.82888126 , 17 , 17 , 0
5289.84818625 , 19 , 19 , 0
6161.77394795 , 23 , 20 , 3
6161.77394795 , 23 , 20 , 3

      

0


source







All Articles