Tomer Apel
Tomer Apel

Reputation: 11

grep between two strings if pattern in the middle linux

i want to grep between two strings only if there is a pattern between them. for example, in this text: first wanted string is Start, second is END, and the pattern is 1 2 3 each in a new line.

Start
abc
abc
1
2
3
abc
END
bla
bla
Start
abc
abc
1
2
4
abc
END
bla
bla
Start
abc
abc
1
2
3
abc
abc
END

the result should be:

Start
abc
abc
1
2
3
abc
END

Start
abc
abc
1
2
3
abc
abc
END

thanks!

Upvotes: 0

Views: 1267

Answers (2)

Yury Usishchev
Yury Usishchev

Reputation: 51

sed -ne '/Start/{:a;N;/END/!b a;/\n1\n2\n3\n/p}'

Line by line:

we need only text starting with 'Start':

sed -ne '/Start/{

we found 'Start', now add everything up to 'END' to pattern space;

set label named 'a':

         :a

add next line to pattern space:

         N

if not found 'END' - jump to 'a'

         /END/!b a

now check if we have desired pattern that contain 1 2 3 and print

they will be separated by '\n' as they were on separate lines

         /\n1\n2\n3\n/p
         }'

Upvotes: 2

venusoft
venusoft

Reputation: 150

grep is not suitable, use sed instead

sed -n "/Start/,/END/p" input.txt

should work. I'm assuming input in a file input.txt.

Upvotes: 0

Related Questions