0

I need delete space and value kubernetes from json file with use bash script:

Content json file

Input

 "spec": {
        "finalizers": [
            "kubernetes"
        ]
    },

Ouput

 "spec": {
        "finalizers": []
    },
glenn jackman
  • 4,630
  • 1
  • 17
  • 20

2 Answers2

1

Given "input.json"

{
  "spec": {
          "finalizers": [
              "kubernetes"
          ]
      },
  "other": 42
  }

Then

jq '.spec.finalizers = []' input.json

outputs

{
  "spec": {
    "finalizers": []
  },
  "other": 42
}
glenn jackman
  • 4,630
  • 1
  • 17
  • 20
0

Lets use some sed magic with regex:

echo 'Input "spec": { "finalizers": [ "kubernetes" ] },' | sed -r 's/Input (.* \[) \".*\" (\].*)/\1\2/'

Which returns:

"spec": { "finalizers": [] },

sed -r uses extended regex (-E on osx), and "()" are used for capture groups, which is what the \1 and \2 refers to, so first we capture everything up to "[", then match everything from the "]" until the end.

The downside of this is that your input doesn't look like complete json, so modifying the regex to match the proper input can be much harder.

I would also recommend you to look at jq, the defacto tool for json parsing in CLI.

Fredrik
  • 540
  • 2
  • 13