I want to find the right hand side of an expression in a file and replace its value with something else using sed. With grep, we see

$ grep power TheFile 
power                 = 1

Also with cut, I can access the value

$ grep power TheFile  | cut -d = -f 2

However, I don't know how to pipe that with the sed command. Any idea to accomplish that?

  • Is the "something else" a function of the existing value, or you just want to put some default string as the replacement? Feb 28, 2018 at 20:17
  • No it is just an integer. For example, changing 1 to 2.
    – mahmood
    Feb 28, 2018 at 20:21

2 Answers 2


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.

  • This would also modify lines that start with e.g. power_output.
    – Kusalananda
    Feb 28, 2018 at 20:33
  • 1
    And now, however unlikely, lines that start with power output... But that's nitpicking.
    – Kusalananda
    Feb 28, 2018 at 20:45

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .