I use (\N+\n\N+\n\N+\n)
to capture the 3 first lines of a paragraph. What if I wanted to capture the 10 first lines, would I have to repeat this 10 times ? Is there a shorter way to do this ?
Take for example the following text file :
Lorem ipsum fuga quisquam occaecati officiis eaque pariatur.
Sunt in ea harum optio ducimus.
Iusto est sunt fugiat voluptas aliquid.
MY HEADER LINE
Dolores provident non sapiente rerum quasi voluptatem repudiandae debitis.
Dolores sint aut aut itaque dolorum nulla non vel.
Nobis nostrum necessitatibus est quidem.
Veniam est aperiam consequatur est.
MY HEADER LINE
Sunt ut dolorem est iure est adipisci porro.
Qui occaecati quisquam provident et dicta aperiam.
With Perl I can easily move the 4th line of each paragraph to the top of that paragraph :
$ cat test | perl -00 -pe 's/(\N+\n\N+\n\N+\n)(\N+\n)/$2$1/'
MY HEADER LINE
Lorem ipsum fuga quisquam occaecati officiis eaque pariatur.
Sunt in ea harum optio ducimus.
Iusto est sunt fugiat voluptas aliquid.
Dolores provident non sapiente rerum quasi voluptatem repudiandae debitis.
MY HEADER LINE
Dolores sint aut aut itaque dolorum nulla non vel.
Nobis nostrum necessitatibus est quidem.
Veniam est aperiam consequatur est.
Sunt ut dolorem est iure est adipisci porro.
Qui occaecati quisquam provident et dicta aperiam.
Is there a way to replace (\N+\n\N+\n\N+\n)
with something shorter ?
Perl's regexp engine supports the common {N}
operator for selecting an exact number of repeats. To do this, you need to group the parts you want to match again (and if you don't want to use the grouping parts later, prefix the group with ?:
)):
For example, grouping 10 lines together:
cat /tmp/test | perl -00 -pe 's/((?:\N+\n){10})(\N+\n)/$2$1/'