seaover
seaover

Reputation: 61

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,
  }
]

Upvotes: 6

Views: 167

Answers (2)

Joe
Joe

Reputation: 26

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)

Upvotes: 1

rock321987
rock321987

Reputation: 11032

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\"/}"

Upvotes: 1

Related Questions