Solution to sed error message: “\1 not defined in the RE”

As a quick sed solution, if you get this “\1 not defined in the RE” error message when running a sed script:

$ sed -f sed.cmds c4.in.html > c4.out.html
sed: 2: sed.cmds: \1 not defined in the RE

the problem probably isn’t too bad. For me I usually get the error message when I forget to “escape” parentheses that I use in my search pattern. I usually write this, which is an error:

s/foo(.*)bar/\1/

when I need to write that sed command like this:

s/foo\(.*\)bar/\1/

Note the use of the \ characters in the correct approach.

Note that I keep my sed commands in a file named sed.cmds in the example shown.

Real world example

In a more real-world example, I just wrote this pattern incorrectly:

# wrong
s?<h3 id="toc_.*">(.*)</h3>?<h3>\1<h3>?

After getting the “\1 not defined in the RE” error message, I corrected that search and replace pattern to this:

s?<h3 id="toc_.*">\(.*\)</h3>?<h3>\1<h3>?

and life was good again.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.