diff --git a/README.md b/README.md index 5d2838d..aecbfc9 100644 --- a/README.md +++ b/README.md @@ -95,7 +95,7 @@ catch (error) { Via CLI: ```sh -replace-in-file from to some/file.js,some/**/glob.js +replace-in-file from to some/file.js,some/**/glob.js [--isRegex] ``` The options `allowEmptyPaths` and `encoding` are supported in the CLI. @@ -103,6 +103,8 @@ In addition, the CLI supports the `verbose` option to list the changed files. Multiple files or globs can be replaced by providing a comma separated list. +A regular expression may be used for the `from` parameter by specifying the `--isRegex` option. + ## License (MIT License) diff --git a/bin/cli.js b/bin/cli.js index a5a99a5..0c7b06d 100755 --- a/bin/cli.js +++ b/bin/cli.js @@ -15,7 +15,7 @@ if (argv._.length < 3) { } //Collect main arguments -const from = argv._.shift(); +let from = argv._.shift(); const to = argv._.shift(); //Single star globs already get expanded in the command line @@ -23,6 +23,19 @@ const files = argv._.reduce((files, file) => { return files.concat(file.split(',')); }, []); +// If the --isRegex flag is passed, send the 'from' parameter +// to the lib as a RegExp object +if (argv.isRegex) { + const flags = from.replace(/.*\/([gimy]*)$/, '$1'); + const pattern = from.replace(new RegExp(`^/(.*?)/${flags}$`), '$1'); + try { + from = new RegExp(pattern, flags); + } + catch (error) { + console.error('Could not create RegExp from \'from\' parameter', error); + } +} + //Log console.log(`Replacing '${from}' with '${to}'`);