Today I Learned

hashrocket A Hashrocket project

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
Bash

So what if I want all the lines from orange to kiwi?

$ echo 'apple\norange\nbanana\nkiwi' | rg 'orange.*kiwi'
Bash

This finds nothing! Never fear, there is a --multiline flag.

$ echo 'apple\norange\nbanana\nkiwi' | rg --multiline 'orange.*kiwi'
Bash

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
Bash

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
Bash

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
Bash
See More #command-line TILs