1

I've been playing with the following regex to cut some content from a markdown file for me which works great in regex101 but can't seem to get grep to work with it.

Either it errors or doesn't return anything

The Regex is here: https://regex101.com/r/XDImM9/1 or (?s)##\s\[v0.0.1].+?(?=---)

I've tried using grep with the -P flag which should support PCRE style regex but doesn't seem to do much grep -P 'm/(?s)##\s\[v0.0.1].+?(?=---)/' CHANAGELOG.md

The sample data I have been working on is

# Changelog All notable changes to this project will be documented in this file. Please note that all entries must end with `---` to allow for the auto release body to use the Changelog ## [v0.0.1] ### Added - Initial Commit/Release --- 

2 Answers 2

1

The two main issues I see here are:

  1. The enclosing m/ and / are regular expression delimiters – they should not be included as part of the regular expression itself.

  2. grep is line-oriented by default, so it doesn't really do multi-line matching. At least in GNU grep, you can use null byte delimiting to kludge it, by adding the -z flag.

So for example,

$ grep -zPo '(?s)##\s\[v0.0.1].+?(?=---)' CHANGELOG.md ## [v0.0.1] ### Added - Initial Commit/Release 

For multi-line matching, you might consider using pcregrep if it is available for your platform, i.e.

pcregrep -Mo '(?s)##\s\[v0.0.1].+?(?=---)' CHANGELOG.md 
1
  • Cheers will just use the pcregrep, its only for a build container so easy enough to add to it. Commented Dec 19, 2019 at 0:22
1

You have to remove m// delimiter, so :

grep -P '(?s)##\s\[v0.0.1].+?(?=---)' CHANAGELOG.md 

But is not suited to be in multi-line mode by default, like in your regex101 snippet.

So, to the rescue :

perl -0 -lne 'print $& if m/(?s)##\s\[v0.0.1].+?(?=---)/' file 

Output

## [v0.0.1] ### Added - Initial Commit/Release 
2
  • Yeah have tried that, still returns nothing. Commented Dec 19, 2019 at 0:14
  • POST edited with perl's solution (multiline mode) Commented Dec 19, 2019 at 0:17

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.