How to do a multiline search in less

gnuless

In less, can you search using / for a pattern that contains a carriage return and newline? I know your pattern can end with a line using $ (from How do I include newlines in a search in less?), but I need the pattern to match text that spans multiple lines.

I tried \n, but that only searches for the n character.

Best Answer

It is not possible to match across line boundaries, because the search function in less operates on a single newline-delimited line at a time. This is the case regardless of the system regex implementation (GNU, POSIX, PCRE, etc.).

Please note that I couldn't find an official source repository for the mainline development of less, but for purposes of code review here, the links that follow are from the FreeBSD contrib tree.

See search.c:search_range() for the implementation of the search operation. The loop therein calls line.c:forw_raw_line() to retrieve the next newline-delimited block of content. That block is passed to match.c:match_pattern() where the search pattern (regular expression) is executed.

To match across multiple lines, you'll need to use a different tool. One option is to drop into your editor and use its search capabilities as suggested by others. You can invoke the editor by pressing v in less.

Related Question