Ketan Bijwe
Ketan Bijwe

Reputation: 77

How to replace text in json using bash

I am trying to replace qa_test_services by test_services using bash in JSON file, could someone please help me with this ? thanks

JSON file - variables.json

{
    "variable": {
        "qa_test_services": {
            "default": {
                "prod-test-1": {
                    "position": 0,
                    "service_name": "test-1-service"
                },
                "prod-test-2": {
                    "position": 1,
                    "service_name": "test-2-service"
                }
            }
        }
    }
}

bash - script

test_json="variables.json"
actual_text="qa_test_services"
replace_text="test_services"

SEARCH_LINE=`cat $test_json | grep $actual_text | sed 's/"//g' | sed 's/://g' | sed 's/{//g' | sed -e 's/  */ /g'`
echo $SEARCH_LINE

Upvotes: 1

Views: 3401

Answers (3)

Jay Mee
Jay Mee

Reputation: 55

This is another example using escape chars as I needed this, thought it would help someone else!

sed 's/\/sounds/\/apps\/soundboard\/sounds/' soundboard.json > test_json_new

Upvotes: 0

Cole Tierney
Cole Tierney

Reputation: 10324

I would avoid the temptation to edit json with line oriented tools. Like xml, It will not always be nicely formatted. Try using jq; it's like sed for json.

jq -f filter.jq variables.json

filter.jq

.variable |= with_entries(
    if .key == "qa_test_services" then
        .key = "test_services"
    else
        .
    end)

output

{
  "variable": {
    "test_services": {
      "default": {
        "prod-test-1": {
          "position": 0,
          "service_name": "test-1-service"
        },
        "prod-test-2": {
          "position": 1,
          "service_name": "test-2-service"
        }
      }
    }
  }
}

using bash variables

jq ".variable |= with_entries(
    if .key == \"$actual_text\" then
        .key = \"$replace_text\"
    else
        .
    end)" $test_json

Upvotes: 4

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179219

If the string you want to replace is exactly that, you could just use this simple sed command:

$ sed 's/qa_test_services/test_services/' variables.json
{
  "variable": {
    "test_services": {
      "default": {
        "prod-test-1": {
          "position": 0,
          "service_name": "test-1-service"
        },
        "prod-test-2": {
          "position": 1,
          "service_name": "test-2-service"
        }
      }
    }
  }
}

If you're happy with the result you can either pipe the output to a different file:

sed 's/qa_test_services/test_services/' variables.json > replaced.json

Or instruct sed to modify the file in-place:

sed -i .backup 's/qa_test_services/test_services/' variables.json

Where .backup is the extension that sed should use for the backup file it creates.

Upvotes: 1

Related Questions