1

I have to modify some paramteres in a param file that may look like:

MY_VAR=YES

I want to use `sed and came up with this:

sed -i 's/MY_VAR=[A-Z]*/MY_VAR=NO/' sed.txt whih seems to work, now I also want it to match if the file looks like

MY_VAR = YES

or any other whitespace fomatting, how do I do that? I tried sed -i 's/MY_VAR\s=\s[A-Z]*/MY_VAR=NO/' sed.txt but that didn't work. How do I do this correctly?

Testix
  • 73
  • 2
  • 6

2 Answers2

5

It seems as if the only blanks that you need to match are the ones between the variable name and the equal sign. Whatever comes after the equal sign will be replaced anyway.

Using standard sed:

sed 's/^\(MY_VAR\)[[:blank:]]*=.*/\1=NO/' params.txt

The [[:blank:]]* sub-expression will match zero or more blank characters. A "blank character" is a tab or a space. The substitution replaces the the whole line that starts with the variable's name followed by optional blanks and a = with the variable's name and the string =NO.

Testing:

$ cat params.txt
MY_VAR=YES
MY_VAR = MAYBE
MY_VAR  =       OK
$ sed 's/^\(MY_VAR\)[[:blank:]]*=.*/\1=NO/' params.txt
MY_VAR=NO
MY_VAR=NO
MY_VAR=NO

For in-place editing of the params.txt file, use -i correctly depending on what sed you use (see How can I achieve portability with sed -i (in-place editing)?), or use

cp params.txt params.txt.tmp &&
sed 's/^\(MY_VAR\)[[:blank:]]*=.*/\1=NO/' params.txt.tmp >params.txt &&
rm -f params.txt.tmp
Kusalananda
  • 333,661
3

Add wildcard to \s. This will cover zero or more spaces. Your command will then be:

sed -i 's/MY_VAR\s*=\s*[A-Z]*/MY_VAR=NO/' sed.txt
hakskel
  • 302