Replacing a string with quotes selectively using sed

10,609

Use an address. The quotes are not a problem if you single quote your sed expression

$ sed '/"foo"/ s/false/true/' file
"bar":  false
"foo":  true

If you really need to match the whole pattern, fine:

$ sed '/"foo": *false/ s/false/true/' file
"bar":  false
"foo":  true

* matches any number of the preceding character (space).

You can use \s to also match tabs (any horizontal whitespace):

sed '/"foo":\s*false/ s/false/true/' file

Add the -i option after testing to modify the original file.

Share:
10,609

Related videos on Youtube

Josef Klimuk
Author by

Josef Klimuk

Updated on September 18, 2022

Comments

  • Josef Klimuk
    Josef Klimuk over 1 year

    I have a file.

    $ cat file
    "bar":  false
    "foo":  false
    

    I need to replace the word false with true only in the pattern "foo": false. The problem is quotes and spaces.

    I thought about two ways:

    1. To isolate the whole pattern in some sort of qoutes/double quotes.
    2. To replace only such "false" which has a "foo" before it.

    An example try of 2 option:

    $ sed -i 's/\(.*foo\)/false/true\1/g' file
    

    It failed.

  • Zanna
    Zanna almost 6 years
    Most welcome, thanks for asking :) @JosefKlimuk