Skip to content

Commit

Permalink
fix: sed works with slashes in regex (#77)
Browse files Browse the repository at this point in the history
  • Loading branch information
nfischer authored Aug 18, 2016
1 parent 1fe09e3 commit e25e567
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
9 changes: 6 additions & 3 deletions src/shx.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,13 @@ export const shx = (argv) => {
newArgs = [];
let lookingForSubstString = true;
args.forEach((arg) => {
const match = arg.match(/^s\/(.*)\/(.*)\/(g?)$/);
const match = arg.match(/^s\/(.*[^\\])\/(.*[^\\])\/(g?)$/);
if (match && lookingForSubstString) {
newArgs.push(new RegExp(match[1], match[3]));
newArgs.push(match[2]);
const regexString = match[1].replace(/\\\//g, '/');
const replacement = match[2].replace(/\\\//g, '/').replace(/\\./g, '.');
const regexFlags = match[3];
newArgs.push(new RegExp(regexString, regexFlags));
newArgs.push(replacement);
lookingForSubstString = false;
} else {
newArgs.push(arg);
Expand Down
17 changes: 16 additions & 1 deletion test/specs/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ describe('cli', () => {
describe('sed', () => {
const testFileName1 = 'foo.txt';
const testFileName2 = 's/weirdfile/name/g';
const testFileName3 = 'urls.txt';
beforeEach(() => {
// create test files
shell.touch(testFileName1);
Expand All @@ -140,11 +141,15 @@ describe('cli', () => {
shell.mkdir('-p', 's/weirdfile/name');
shell.touch(testFileName2);
shell.ShellString('foo\nfoosomething\nfoofoosomething\n').to(testFileName2);

shell.touch(testFileName3);
shell.ShellString('http://www.nochange.com\nhttp://www.google.com\n').to(testFileName3);
});

afterEach(() => {
shell.rm('-f', testFileName1);
shell.rm('-rf', 's/');
shell.rm('-rf', 's/'); // For testFileName2
shell.rm('-f', testFileName3);
});

it('works with no /g and no -i', () => {
Expand All @@ -159,6 +164,16 @@ describe('cli', () => {
shell.cat(testFileName1).stdout.should.equal('bar\nbarsomething\nbarbarsomething\n');
});

it('works with regexes conatining slashes', () => {
const output = cli(
'sed',
's/http:\\/\\/www\\.google\\.com/https:\\/\\/www\\.facebook\\.com/',
testFileName3
);
output.stdout.should.equal('http://www.nochange.com\nhttps://www.facebook.com\n');
shell.cat(testFileName3).stdout.should.equal('http://www.nochange.com\nhttp://www.google.com\n');
});

it('works with weird file names', () => {
const output = cli('sed', 's/foo/bar/', testFileName2);
output.stdout.should.equal('bar\nbarsomething\nbarfoosomething\n');
Expand Down

0 comments on commit e25e567

Please sign in to comment.