I want to retrieve all foo.bar lines where within the block following themselves and before the next foo.bar there is a line stating relevant=yes.
So the output should be:
I could of course write a program/script iterating through the lines, remembering the foo.bars and print them when there is a line saying relevant=yes following them an before the next foo.bar. But I thought there might be an out-of-the box way using standard Unix utilities (grep/sed/awk)?
sed '/foo\.bar/h;/relevant=yes/!d;x;/foo\.bar/!d' infile
Lines matching foobar are copied to hold space. All lines, except those matching relevant=yes are deleted. Exchange hold space with pattern space (this only happens when lines match relevant=yes) and delete if it doesn't match foobar.
>>> with open("/home/xieerqi/textfile.txt") as file:
... for line in file:
... if line.__contains__("foo"):
... VAR = line
... if line.__contains__("relevant=yes"):
... print VAR
Put together in a script:
skolodya@ubuntu:$ chmod +x relevance.py
skolodya@ubuntu:$ ./relevance.py textfile.txt
skolodya@ubuntu:$ cat relevance.py
with open(sys.argv) as file:
for line in file:
VAR = line.strip("\n")