linuxreplacesedfindvi

Sed replace characters in a string


I've got a file with a string (the 1,2,3 will vary):

{"var": [1,2,3]}

I want to replace it to look like so:

{"var": [4,5,6]}

I try this:

sed 's/\{"var": \[.*\]\}/\{"var": \[4,5,6\]\}/g' file.txt

But I get an error:

 Invalid preceding regular expression

How can I replace the string?


Solution

  • Sed uses some unusual escaping style: you (usually) escape symbols to make them "active", otherwise they are just characters.

    So, this one works properly (without escaping the braces, plus, you're missing a dot)

    sed 's/{"var": \[.*\]\}/\{"var": \[4,5,6\]}/g' file.txt
    

    however, I'd recommend you not to do so, ie. use a proper json parser to open the file, change it, and save it back again.