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.
Related videos on Youtube
Author by
Josef Klimuk
Updated on September 18, 2022Comments
-
Josef Klimuk over 1 year
I have a file.
$ cat file "bar": false "foo": false
I need to replace the word
false
withtrue
only in the pattern"foo": false
. The problem is quotes and spaces.I thought about two ways:
- To isolate the whole pattern in some sort of qoutes/double quotes.
- 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 almost 6 yearsMost welcome, thanks for asking :) @JosefKlimuk