0

I have a config.js file which contents below strings

.constant('Digin_Engine_API', 'http://local.net:1929/')

I want to read this file and replace what ever the things which are there after the .constant('Digin_Engine_API'I tried using sedbut ddnt worked. This is what I used for sed

sed -i 's/^.constant('Digin_Engine_API', .*/http://cloud.lk:8080/' /var/config.js

As a summary my final out put (config.js) file needs to consists below.

Before

.constant('Digin_Engine_API', 'http://local.net:1929/')

After

.constant('Digin_Engine_API', 'http://cloud.lk:8080/')

2 Answers2

1
  • You need to use double quotes around sed command since single quote is part of pattern
  • You should use an alternate delimiter since / is used in replacement
  • You need to capture the first part and use it in replacement
  • You need to quote the replacement and also add closing )

Sed command:

sed -i.bak "s~\(\.constant('Digin_Engine_API', \).*~\1'http://cloud.lk:8080')~" /var/config.js

cat /var/config.js

.constant('Digin_Engine_API', 'http://cloud.lk:8080')
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    Faster than me to write it up haha :D – joaumg Dec 09 '16 at 11:16
  • @anubhava I tried this and it worked fine. But my typical config.js file has lot of lines. All have different string patterns. But when it comes to full config.js this is not working. any Idea for that ? This is my typical config.js file. https://www.dropbox.com/s/6hhmzjpfgmnvt8z/config.js?dl=0 –  Dec 09 '16 at 11:37
  • That is because you have some spaces before `.constant`. You can just use `sed "s~\(\.constant('Digin_Engine_API', \).*~\1'http://cloud.lk:8080')~" config.js` – anubhava Dec 09 '16 at 15:14
0

Here you are:

sed -i -r "s_(\.constant\('Digin_Engine_API').*_\1, <new content>)_" file

Remarks

  • you cannot use ' in sed command if command is surrounded by '' also,
  • you must escape all ( and ) that are part or string, and not the sed grouping command,
  • you must escape . character, because it is also sed replacement for every char,
  • you must use another sed s separator instead of / if you need to use / in that command, but you can also escape / by \/.
Marek Nowaczyk
  • 257
  • 1
  • 5