0

I need to replace value with new_value in strings

key:value
key: value
key:  value

To get

key:new_value
key: new_value
key:  new_value

Number of spaces after : is arbitrary. The regex to match would be key: *value. How do I replace value with new_value in such strings preserving number of spaces with sed?

To clarify, key1:value or key:value1 do not match due to different key/value, so such strings are not altered.

2 Answers 2

2

Try -

sed 's/^\(key: *\)value/\1new_vale/' file
Sign up to request clarification or add additional context in comments.

2 Comments

No need in g at the end: sed '.../g' ?
No, trailing g not required here. To understand what g does, try out the following two commands: foo="aaaa"; echo $foo | sed 's/a/X'; echo $foo | sed 's/a/X/g'
0

You may use this sed to match all cases:

sed -E 's/^([[:blank:]]*key[[:blank:]]*:[[:blank:]]*)value([[:blank:]]|$)/\1new_value/' file
key:new_value
key: new_value
key:  new_value

This allows 0 or more whitespaces at:

  • before key at start
  • between key and :
  • between : and value
  • after value before end
  • [[:blank:]] matches a space or a tab

4 Comments

No need in g at the end: sed -E '.../g' ?
But I don't have /g at the end
Not my downvote. Good answer. I was asking if 'g' is needed in the end to process all matches, as it is usually done.
@user2052436 g is for when you need to process multiple matches on a line. Per the sample input in your question you don't have any cases where there are multiple matches on a line and so specifying g wouldn't make sense. If that's wrong then, of course, fix the example in your question.

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.