Sed command to add a character when pattern is matched?

Viewed 42

I have the contents of file like:

data {
    x = "name",
    y = "job"
    z = "role"
  }

I want to add = in front of the curly bracket when it is missing, otherwise ignore it

Output should be :

data = {
    x = "name",
    y = "job"
    z = "role"
  }

I tried this but doesn't work. sed -r -ie 's|data \{ | data \= \{|g' abc.txt

Can anybody please tell what am I doing wrong?

Thanks

2 Answers

You can use

sed -r -i 's|(data)[[:space:]]*(\{)|\1 = \2|g' abc.txt
sed -i 's|data[[:space:]]*\{|data = {|g' abc.txt

Details:

  • -r (or -E) option enables POSIX ERE regex syntax
  • (data)[[:space:]]*(\{) - matches and captures data into Group 1, [[:space:]]* matches any zero or more whitespaces, (\{) captures into Group 2 a { char
  • \1 = \2 - replaces with Group 1 value, space, =, space and Group 2 value.

See an online demo.

NOTE: If you need to make sure the pattern matches the whole line add anchors, ^ and $:

's|^(data)[[:space:]]*(\{)$|\1 = \2|g'

In a GNU sed, you may use a shorter form for [[:spaces:]]*, \s*:

's|^(data)\s*(\{)$|\1 = \2|'

If there can be leading/trailing whitespace and you need to keep it use:

's|^(\s*data)\s*(\{\s*)$|\1 = \2|'

sed '/=/!s/data /&= /' abc.txt

On lines not having an equal sign, replace data+space with data+space+equal+space.

Related