Ladislav M
Ladislav M

Reputation: 2187

Replacing code between two JavaScript comments

I need to set a value of JavaScript variable from bash. Variable lives in index.html file and I'd like to use unix SED command to do that. Inside index.html I have it lake this:

<script>
/*bash_var*/ var foo = 1;  /*end_bash_var*/
</script>

I tried to do it like this:

sed -i -e 's%/*bash_var*/(.*)/*end_bash_var*//'"$ var foo = 0; /g" index.html

and few more variations of this command, but I alway get some error.

Thanks for any help.

Update

Expected output:

<script>
/*bash_var*/ var foo = 0;  /*end_bash_var*/
</script>

Upvotes: 0

Views: 105

Answers (2)

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed 's#\(/\*bash_var\*/ *var foo = \).*\(; */\*end_bash_var\*/\)#\10\2#'

If it is just the value of the foo in this context

Upvotes: 1

pfnuesel
pfnuesel

Reputation: 15340

You need to escape the *. Moreover your ' are wrong and there's no need for a %.

sed 's#\(/\*bash_var\*/\).*\(/\*end_bash_var\*/\)#\1 var foo = 0; \2#'

Note that I use # as delimiters, rather than /. This way I can use / in my expressions without escaping them. This makes the sed command a little bit more readable. However, this is still tedious. Can you rewrite your index.htm into something like this?

<script>
//BASHVAR
var foo = 1;
</script>

Then you can use

sed '/BASHVAR/{n; s/.*/var foo = 0;/;}'

Upvotes: 1

Related Questions