Python solution:
$ ./find_bound_pattern.py < input.txt
startStr
aaa
bbb
ccc
endStr
Script itself:
#!/usr/bin/env python
from __future__ import print_function
import sys
flag = None
group = []
for line in sys.stdin:
if 'startStr' == line.strip():
flag = True # mark beginning of the block
group.append(line.strip())
continue
if flag: # we are in a block, so record lines
group.append(line.strip())
if 'endStr' == line.strip():
flag = False # reached end of block, time to check
if 'bbb' in group:
print('\n'.join(group))
group = [] # clear list after each block end
The way this works is quite simple: we mark the beginning of the block with flag
variable, and unset it once we reach end of block. Once we reach end of block - we check what we recorded for presence of bbb
, and print out all the strings. The recorded list is cleared at the end of each block and process repeats again, so this is suitable for matching multiple blocks which may contain bbb
.
The logic in this approach is simple, can be implemented with other languages such as C, Java, or Ruby - whichever your heart desires. Note that in this case, this is more of a line-matching problem, but if there is a need for more advanced pattern matching, it can be implemented as well via re
module.
sed
? – jimmij Jan 06 '17 at 22:41