简体   繁体   中英

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?

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.

Try this :

sed -r 's@(\{"var": \[)[^\]+\]@\14,5,6]}@' file.txt

output

{"var": [4,5,6]}}
  • { } & [ ] need backslashing, because it some keywords in sed regex
  • the -r means extented regex , this need less backslashing.

Check this out:

echo '{"var": [1,2,3]}' | sed 's/{"var": \[.*\]}/\{"var": \[4,5,6\]\}/g

You need .* to match zero or more occurences of any character. Also, I unescaped the curly braces; I'm not sure they needed to be escaped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM