0

I want to replace a string ip_ttl="1" with ip_ttl="2" using sed.

I've tried sed -i "s/ip_ttl="1"/ip_ttl="2"/g" - but its not working.

Please help!

3
  • 1
    Would fit best at SuperUser or Unix & Linux. Commented Mar 27, 2015 at 6:53
  • If you do that you are opening and closing the thing twice. You have to use a different type of quotation marks Commented Mar 27, 2015 at 6:54
  • 1
    @mins This question could be here since it is coding (source of code) problem not simply a unix problem (even if the real problem is a shell interpretation in this case, know from the OP only when solution is provided) Commented Mar 27, 2015 at 13:48

3 Answers 3

2

Put your sed code inside single quotes, because your code already contains double quotes.

sed -i 's/ip_ttl="1"/ip_ttl="2"/g' file

If you put your code within two double quotes, sed would terminate the program once another double quote was reached. So " before 1 was reached, it would consider as the end and terminates the program.

Update:

If the number always changes then it's better to define the pattern which matches any number.

sed -i 's/ip_ttl="[0-9]\+"/ip_ttl="2"/g' file
Sign up to request clarification or add additional context in comments.

1 Comment

one more thing ip_ttl="1" will get changed from 1 to 0 or any number - should replace with ip_ttl="2"
1

If you are using quotation marks in your pattern either escape double quotes in pattern:

sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g"

or enclose whole pattern in single quotes:

sed -i 's/ip_ttl="1"/ip_ttl="2"/g'

2 Comments

we have one more problem - trying to replace timeToLive=99(dynamic value it it) with timeToLive=0 from the file , the format sed -i 's/timeToLive=*/timeToLive=0/g' is not replacing properly, please suggest
sed -i 's/timeToLive=[0-9]\+/timeToLive=0/g'
0

Alternatively you can escape the quotation marks

sed -i "s/ip_ttl=\"1\"/ip_ttl=\"2\"/g" file

Sometimes that's useful because you have both single and double quotes in a string you're selecting for.

1 Comment

Welcome to regex. I did say "alternatively" because I agree, it does make it complex but you can't escape escaping.

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.