Sed is the address space between "{" and "},"

I am specifying the address space between "{" and "}" in sed, so I expect that only the first "Acer" will be replaced by "TTTT". The second is not expected. How can I fix this problem? I tested Ubuntu 15.10 and sed version is sed (GNU sed) 4.2.2.

Thanks in advance.

$ echo " [ { \"manufacturer\": \"Acer\", \"regularPrice\": 165.99, }, [ \"manufacturer\": \"Acer\", \"regularPrice\": 165.99, ], { \"manufacturer\": \"Acer\", \"regularPrice\": 165.99, } ] " | sed "/{/,/},/ {s/\"Acer\"/\"TTTT\"/}" 

Its results are as follows:

 [ { "manufacturer": "TTTT", "regularPrice": 165.99, }, [ "manufacturer": "Acer", "regularPrice": 165.99, ], { "manufacturer": "TTTT", "regularPrice": 165.99, } ] 
+5
source share
2 answers

This will only work for GNU sed

 sed "/{/,/},/ {0,/\"Acer\"/ s/\"Acer\"/\"TTTT\"/}" 

or rather, also works

 sed "/{/,/},/ {0,/\"Acer\"/s//\"TTTT\"/}" 
+1
source
 echo ' [ { "manufacturer": "Acer", "regularPrice": 165.99, }, [ "manufacturer": "Acer", "regularPrice": 165.99, ], { "manufacturer": "Acer", "regularPrice": 165.99, } ] ' | perl -0777 -pe 's/({[^}]*)"Acer"([^{]*?},)/$1"TTTT"$2/gs' 

I used perl v5.16.3 here, which returns the following:

 [ { "manufacturer": "TTTT", "regularPrice": 165.99, }, [ "manufacturer": "Acer", "regularPrice": 165.99, ], { "manufacturer": "Acer", "regularPrice": 165.99, } ] 

Note:

  • -0777 slurp whole file
  • -p iterate over lines and print them
  • -e code on the command line
  • wildcard (s ///) globally (g) and allow wildcards to match newlines
+1
source

Source: https://habr.com/ru/post/1246202/


All Articles