0

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>
5
  • What's your expected output? Commented Nov 5, 2014 at 15:13
  • Mind sharing what error you are receiving? Commented Nov 5, 2014 at 15:13
  • Why not use a JavaScript parser & code generator to do this for you? Use acorn and escodegen. Commented Nov 5, 2014 at 15:15
  • errors like 'unterminated substitute pattern' or 'parentheses not balanced' Commented Nov 5, 2014 at 15:22
  • And can you write a full answer using acorn and escodegen? Commented Nov 5, 2014 at 15:23

2 Answers 2

1

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;/;}'
Sign up to request clarification or add additional context in comments.

5 Comments

Sure, I can rewrite it like that, but BASHVAR string need to be under inside inline or block comments.
I'm getting "/BASHVAR/{n; s/.*/var f ...": bad flag in substitute command: '}'
What version of sed are you using? It works for me on GNU sed 4.2.2. Can you try again?
I'm not sure, how can I display the version of sed. But I'm runnig OS X 10.9.
Okay, I'm not much help, since I don't have access to your version of sed. Did you try the last command again? I changed it slightly.
1
sed 's#\(/\*bash_var\*/ *var foo = \).*\(; */\*end_bash_var\*/\)#\10\2#'

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.