Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sed to Replace & and slashes

I have a data in below format.

  new_name='abc &eft /  def \ mno' 

 1.json
  {
    "text": {
              "attribute": "old_name",
              "data": "xyz"
             }
  }

I am trying to replace the value old_name by new_name.

My trail :–

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 sed  "s/old_name/${new_name/&/\&}; s/old_name/${new_name////\/}/g" 1.json

I get below error :–

 sed: -e expression #1, char 67: unknown option to `s'

Any guidance would be of great help.

>Solution :

You can skip the need to escape the slash by using a different delimiter for the substitution, but you still need to do one of the other replacements outside the sed command:

new_name='abc &eft /  def \ mno'
quoted=${new_name/\\/\\\\\\\\}
sed "s=old_name=${quoted//&/\\&}=g" 1.json

But jq is far better tool to handle json:

new_name='abc &eft /  def \ mno'
jq --arg n "$new_name" \
    '.text.attribute |= (if . == "old_name" then $n else . end)' 1.json
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading