2

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")
aa
bb
cc

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")
aa

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) – Christian Brabandt Oct 17 '15 at 7:05
  • Is their another way to do multi line search without having to use ex command, more specifically in the command mode? – Stephen Jacob May 22 '17 at 9:51
3

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, privacy policy and cookie policy

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