14wml
14wml

Reputation: 4166

\1 not defined in the RE

In my script, I'm in passing a markdown file and using sed, I'm trying to find lines that do not have one or more # and are not empty lines and then surround those lines with <p></p> tags

My reasoning:

^[^#]+ At beginning of line, find lines that do not begin with 1 or more #

.\+ Then find lines that contain one or more character (aka not empty lines)

Then replace the matched line with <p>\1</p>, where \1 represents the matched line.

However, I'm getting "\1 not defined in the RE". Is my reasoning above correct and how do I fix this error?

BODY=$(sed -E 's/^[^#]+.\+/<p>\1</p>/g' "$1")

Upvotes: 1

Views: 1126

Answers (1)

Barmar
Barmar

Reputation: 780724

Backslash followed by a number is replaced with the match for the Nth capture group in the regexp, but your regexp has no capture groups.

If you want to replace the entire match, use &:

BODY=$(sed -E 's%^[^#].*%<p>&</p>%' "$1")

You don't need to use .+ to find non-empty lines -- the fact that it has a character at the beginning that doesn't match # means it's not empty. And you don't need + after [^#] -- all you care is that the first character isn't #. You also don't need the g modifier when the regexp matches the entire line -- that's only needed to replace multiple matches per line.

And since your replacement string contains /, you need to either escape it or change the delimiter to some other character.

Upvotes: 3

Related Questions