1

Would like to write a bash script that replaces some strings in a text file, however I am getting hung up on how to replace the contents inside a 'value' for a variable.

Suppose the value I wish to set inside a text file could be :

TCP_IN = "123,35,995"

.. where 123,35,995 could be any string (not just numbers with commas.

How could I replace this keypair searching for TCP_IN = "*" and set the value inside where * is, from within a bash script ?

4
  • 1
    Check this demo Commented Mar 8, 2016 at 17:43
  • Awesome :) .. Thank you very much !!!!! Commented Mar 8, 2016 at 17:48
  • @WiktorStribiżew Why not an answer here? Commented Mar 8, 2016 at 17:52
  • 2
    Posted and explained a little. Commented Mar 8, 2016 at 17:59

1 Answer 1

1

You can use

sed -E 's/(TCP_IN *= *")[^"]+/\1MyNewVal/g'

See the IDEONE demo

The regex matches and captures into Group 1 TCP_IN followed with zero or more spaces, followed with a = symbol, followed with again zero or more spaces, and then [^"]+ matches 1 or more characters other than a " ([^...] is a *negated character class that matches all characters but those defined inside the char class).

Sign up to request clarification or add additional context in comments.

5 Comments

Just a quick note on this, to use a variable named MyNewVal, you can do it as follows : sed -E 's/(TCP_IN *= *")[^"]+/\1'$MyNewVal'/g'
i have a small issue with running multiple of these consecutively. ideone.com/xUuhMq results in zeroing the file size.
I am not sure what you mean, none of the variables have ' in them ? The syntax works > ideone.com/0j1VDt . Only once, not when run consecutively. :)
Sorry, missed the first comment. Just a sec.
No problem, I posted this as a question here, stackoverflow.com/questions/35876027/…

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.