Multiline matches with ripgrep (rg)
Ripgrep has become the default file search tool in my development environment. It's fast! It can also do multiline searches if given the correct set of flags.
First, let me introduce you to the dataset:
$ echo 'apple\norange\nbanana\nkiwi'
apple
orange
banana
kiwi
So what if I want all the lines from orange
to kiwi
?
$ echo 'apple\norange\nbanana\nkiwi' | rg 'orange.*kiwi'
This finds nothing! Never fear, there is a --multiline
flag.
$ echo 'apple\norange\nbanana\nkiwi' | rg --multiline 'orange.*kiwi'
This also finds nothing! The problem is that .
does not match \n
in regex. You can change that behaviour however by using the dot all
modifier which looks like (?s)
.
$ echo 'apple\norange\nbanana\nkiwi' | rg --multiline '(?s)orange.*kiwi'
orange
banana
kiwi
We did it! Alternately, you can use the --multiline-dotall
flag to allow .
to match \n
.
$ echo 'apple\norange\nbanana\nkiwi' | rg --multiline --multiline-dotall 'orange.*kiwi'
orange
banana
kiwi
I prefer short incantations however, and we can shorten it by using -U
instead of --multiline
.
$ echo 'apple\norange\nbanana\nkiwi' | rg -U '(?s)orange.*kiwi'
orange
banana
kiwi
Tweet