11

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
 1

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

don_crissti
  • 82,805
mahmood
  • 1,211

2 Answers2

13

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.

user1404316
  • 3,078
6

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
Kusalananda
  • 333,661