Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/shx.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ const convertSedRegex = (args) => {
const match = arg.match(new RegExp(sedPattern));
if (match && lookingForSubstString) {
const regexString = match[1].replace(/\\\//g, '/');
const replacement = match[2].replace(/\\\//g, '/').replace(/\\./g, '.');
// Unescape in one pass so an escaped backslash cannot escape the next character.
const replacement = match[2].replace(/\\(.)/g, '$1');
const regexFlags = match[3];
if (regexString === '') {
// Unix sed gives an error if the pattern is the empty string, so we
Expand Down
28 changes: 28 additions & 0 deletions test/specs/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,34 @@ describe('cli', () => {
shell.cat(testFileName4).stdout.should.equal(testContents4);
});

it('preserves escaped backslashes in replacement strings', () => {
const output = cli('sed', String.raw`s/foo/C:\\temp\\file.txt/`, testFileName1);
output.stdout.should.equal(
'C:\\temp\\file.txt\nC:\\temp\\file.txtsomething\nC:\\temp\\file.txtfoosomething\n',
);
output.code.should.equal(0);
output.stderr.should.equal('');
shell.cat(testFileName1).stdout.should.equal(testContents1);
});

it('unescapes adjacent backslashes and slashes only once', () => {
mocks.stdin('foo\n');
const output = cli('sed', String.raw`s/foo/\\\/path/g`);
output.stdout.should.equal('\\/path\n');
output.code.should.equal(0);
output.stderr.should.equal('');
});

it('preserves escaped backslashes when replacing in place', () => {
const output = cli('sed', '-i', String.raw`s/foo/C:\\temp\\file.txt/g`, testFileName1);
shell.cat(testFileName1).stdout.should.equal(
'C:\\temp\\file.txt\nC:\\temp\\file.txtsomething\nC:\\temp\\file.txtC:\\temp\\file.txtsomething\n',
);
output.stdout.should.equal('');
output.stderr.should.equal('');
output.code.should.equal(0);
});

it('works with empty replacement strings (with /g)', () => {
const output = cli('sed', 's/foo//g', testFileName1);
output.stdout.should
Expand Down