admin admin
admin admin

Reputation: 85

How can i modify a remote file over ssh with sed?

i am trying to add a line to the top of a JS file on a remote server the command i want to run is:

sed -i "1i\const test = require(\'../../../test/test.json\');" /opt/test.js

so i have tried the following:

ssh user@host "sed -i "1i\const test = require(\'../../../test/test.json\');" /opt/test.js"

this gives me an error due to the "(" and ")" so i added a "\" before them:

ssh user@host "sed -i "1i\const test = require\(\'../../../test/test.json\'\);" /opt/test.js"

however i still get the error:

bash: -c: line 0: syntax error near unexpected token `('

how can i fix this?

Upvotes: 0

Views: 603

Answers (1)

chepner
chepner

Reputation: 531165

Rather than use sed -i (which just manages a temp file behind the scenes), use ed and provide the script (via ssh) to ed's standard input.

ssh user@host 'ed /opt/test.js' <<'EOF'
1i
const test = require('../../../test/test.json');
.
wq
EOF

Upvotes: 1

Related Questions