Bash – Grep by block of text\lines

bashscriptingshellshell-scripting

I have the text, that contains some lines. So, i need to make GREP of several lines. For example, i have repeating text and i should GREP get lines, that have this repeating key-words.

grep -o "test|test2" textfile

My text:

123|never for your|test
123421|never for your|test2
123412|never for your|test3
12341|never for your|test4
12311|never for your|test2
123312312|never for your|test
123321312|never for your|test2

I should have:

123|never for your|test
123421|never for your|test2
123312312|never for your|test
123321312|never for your|test2

It works, but it doesn't work how i want. It searchs in text, all words "test" & "test2". But i want to get textblocks, like some pattern, where only after "test" comes "test2".
Have you got any ideas ?

Best Answer

Brief shell script using sed. Makes a list of line numbers for the second case, and compares against line numbers for the first case. Prints matching pairs. Uses the first argument as the file name. Could easily be extended to take second and third arguments as patterns to match. Could save as findnext.sh, and run:

$ sh findnext.sh testfile

Should be quick as it only involves two passes over the file, and has the advantage of being completely portable.

#!/bin/sh 
# Line numbers matching test1
mt2=$(sed -ne '/test1/=' < $1 | tr '\n' '/')

for l in $(sed -ne '/test/=' < $1); do
    nextline=$(expr $l + 1)
    [ "${mt2#*$nextline/}" != "$mt2" ] && sed -ne $l,${nextline}p <$1
done