"key = value" lines: how to replace a specific key's value?

How about:

sed '/^power /s/=.*$/= your-replacement/' TheFile
  1. /^power / is an address specifier, in this case looking for a line that matches a regex ^power.

  2. s is a replacement command, matching a regex being everything after the =.

  3. Note that there is no need to pipe the contents of the file; you can just specify it (or a list of files) as a command argument. If you want / need to pipe something into sed, that's easy - just | sed ...

  4. If the whitespace immediately after the initial word (eg. power) might be a tab, use [[:blank:]] instead. Some versions of sed allow you to use \t for a definite tab character.


To find the lines in TheFile that starts with the word power followed by some amount of whitespace and an equal sign, and to replace whatever comes after that equal sign with something:

sed -E 's/^(power[[:blank:]]*=[[:blank:]]*).*/\1something/' TheFile

[[:blank:]]* matches zero or more spaces or tabs. This preserves the whitespace before and after the =. The \1 in the replacement text will insert the part of the string that is matched by the first parenthesis.

To make the change in place with e.g. GNU sed, add the -i flag, otherwise, redirect the output to a new file.

Testing it:

$ cat TheFile
power                 = 1
power123              = 1
power  123            = 1
power                 =
power                 =                 112

$ sed -E 's/^(power[[:blank:]]*=[[:blank:]]*).*/\1something/' TheFile
power                 = something
power123              = 1
power  123            = 1
power                 =something
power                 =                 something

Tags:

Sed