1

I have a string in a file like this:

"Value1=[random number]"

After this string I want to add another string, specifically:

"Value2=100"

If I try to use:

sed  '/Value1=/a Value2=100' myfile.txt

It will fail because I have not included the fact that Value1=[some random number].

How do I add the condition that Value1=random number and Value2 should be added to this string?

3 Answers 3

1
sed  '/Value1=[0-9]\+/a Value2=100' myfile.txt

The [0-9]\+ will match any string of digits. For example, on my cygwin, GNU sed 4.2.2,

echo Value1=42 | sed '/Value1=[0-9]\+/a Value2=43'

produces

Value1=42
Value2=43

Edit: If the number may or may not be in double-quotes, use:

 sed '/Value1="\?[0-9]\+"\?/a Value2=43'

The "\? is an optional double-quote.

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

1 Comment

What if the number is surrounded by quotes? Does this mean it's no longer a number, but a string?
1

Something like this:

$ sed 's,\(Value1=200\),\1 Value2=100,' myfile.txt

Result:

Value1=200 Value2=100

Comments

1
echo '"Value1=400"' | sed 's/"Value1=.*"/&\n"Value2=100"/'

Output:

"Value1=400"
"Value2=100"

Or:

echo '"Value1=400"' | sed 's/"Value1=.*"/& "Value2=100"/'

Output:

"Value1=400" "Value2=100"

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.