user2052436
user2052436

Reputation: 4765

replace substring in matching string

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.

Upvotes: 0

Views: 583

Answers (2)

anubhava
anubhava

Reputation: 784908

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

Upvotes: 0

Happy Green Kid Naps
Happy Green Kid Naps

Reputation: 1673

Try -

sed 's/^\(key: *\)value/\1new_vale/' file

Upvotes: 2

Related Questions