I've a file where I would like to extract a multiline pattern in non-greedy way (similar to this scenario) by using ex editor.

This example works fine:

$ ex +'/aa/,/cc/p' -scq! <(echo -e "start\naa\nbb\ncc\nend")

by extracting me pattern between aa and cc, but it's uses ranges.

And I would like to extend that example by introducing a multiline non-greedy pattern (\_.\{-}), but it doesn't print for me the whole multi-line match for some reason:

$ ex +'/aa\_.\{-}cc/p' -scq! <(echo -e "start\naa\nbb\ncc\nend")

Is there any reason for that or I'm missing anything? How do I correct that?

  • :p only works on single lines and does not understand multiline patterns. Therefore use ranges. That's what they are for and they are non-greedy by default. (This is also the way sed works) Oct 17, 2015 at 7:05
  • Is their another way to do multi line search without having to use ex command, more specifically in the command mode? May 22, 2017 at 9:51

1 Answer 1


There's something almost perverse in doing this with ex, akin to chopping a tree with a razor blade, or drinking a bucket of water through a straw. But if you stop and think for a few minutes about what you're doing, it's relatively straightforward:

ex +'/aa\_.\{-}cc/' +'normal gny' +new +'normal P' +'%p' -scqa! file

Translation, for the less masochistic among us:

  • + introduce command line statements that apply to file
  • /aa\_.\{-}cc/ searches for the pattern
  • normal gn marks the text just found
  • y yanks said text
  • new opens a new buffer
  • normal P pastes the text
  • %p prints the buffer (i.e. :p applied to the entire buffer, a.k.a. %)
  • -scqa! runs :qa!, i.e. bails out.

The same tricks, using normal <mumble> to get to normal mode commands from within ex, and pasting stuff to a scratch buffer, can be used to solve other similar quizzes, such as printing the contents of a register, and echo-ing things (hint: use redir for that one).

Edit: Alternative approach, by OP:

ex +'sil /aa\_.\{-}cc/norm gny' +'redi>>/dev/stdout|echon @"' -scq! file

Please note that /dev/stdout is not available on all systems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.