Search code examples
regexbashsedcapture-group

Valid RegEx with capture groups, but sed script not working


I have a valid RegEx pattern that captures three groups of a string. I'm trying to use it in a sed script to perform a find & replace operation, but I keep getting the following error:

sed: -e expression #1, char 49: Unmatched ( or \(

My script looks like this:

#!/usr/bin/env bash

pattern="^.*(require\(require\()(.+)(\);$)"
replace="require(\2;"
sed -i "s/$pattern/$replace/g" /usr/lib/node_modules/deployd/lib/type-loader.js

The file I'm trying to edit has a line that reads:

var c = require(require('path').resolve(path) + '/node_modules/' + file);

...and my desired result is:

var c = require('path').resolve(path) + '/node_modules/' + file;

I've confirmed my RegEx here: http://regex101.com/r/qO4jE5/1

...and double-checked it here: http://regexraptor.net/

Any idea what I'm doing wrong?


Solution

  • Normal sed uses BRE, Basic Regular Expressions. In BRE, the capturing groups () must be escaped like this \(,\) and to match a literal ) symbol, just ) would be enough.

    Example:

    $ echo "var c = require(require('path').resolve(path) + '/node_modules/' + file);" | sed 's/^\(.*\)require(require\(.*\));$/\1require\2;/'
    var c = require('path').resolve(path) + '/node_modules/' + file;