Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed - address space between "{" and "},"

I specify the address space between "{" and "}," in sed, so I expect only the first "Acer" to be replaced to "TTTT". Second one is not expected. How can I fix this problem ? I did test on 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,
  }
]
like image 221
seaover Avatar asked Oct 31 '22 06:10

seaover


2 Answers

This will work only for GNU sed

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

or to be more precise the following is also working

sed "/{/,/},/ {0,/\"Acer\"/s//\"TTTT\"/}"
like image 59
rock321987 Avatar answered Nov 01 '22 20:11

rock321987


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 the entire file
  • -p loop over lines and print them
  • -e code in the command line
  • substitution (s///) globally (g) and allow wildcards to match newline chars (s)
like image 21
Joe Avatar answered Nov 01 '22 18:11

Joe