Search code examples
regexbashshellpattern-matchingregular-language

Grep a block of text using pattern


I have short text file, where i should make output of data using special pattern. My file:

99 test1
88 test2
10 test3
11 test1
12 test1
13 test2
14 test3
17 test1
18 test4

One by one, from test1 to test2 and to test3. So... I have written the comand:

sed '/test1.*\|test2.*\|test3/!d' filename

And in output i have result:

99 test1
88 test2
10 test3
11 test1
12 test1
13 test2
14 test3
17 test1

In this case, i have lines, that i not need:

11 test1

17 test1

This lines don't go one after one. How i can do result, that i need ? Please help me. Thanks for your attention. i Should get this result:

99 test1
88 test2
10 test3
12 test1
13 test2
14 test3

Solution

  • A simple quick way, although not very elegant, is to put it in one line, break it in the desired pattern, and then filter it again with the pattern:

    sed ':a;N;$!ba;s/\n/\\n/g' < filename | \
    sed 's/\([0-9][0-9] test1\\n[0-9][0-9] test2\\n[0-9][0-9] test3\\n\)/\n\1\n/g' | \
    egrep "[0-9][0-9] test1\\\n[0-9][0-9] test2\\\n[0-9][0-9] test3\\\n" | \
    sed 's/\\n/\n/g' | grep .