2

I am trying to delete different values from a JSON file. It's not pretty and jq returns 1 compile error. I am searching for a solution from the command-line (awk/sed).

Here is my sample data from my json-file (similiar to docker-compose):

aaaa"MyPorts":{"80/tcp":{},"8080/tcp":{},"9080/tcp":{},"9090/tcp":{}},aaaa  
bbbb"PROTO 9080/tcp 9090/tcp"bbbbb
cccc"TEST PROTO 80 8080"ccccc

All entries can be found multiple times or also within one line.

After using the replace it should look like:

aaaaaaaa  
bbbbbbbbb
cccc"TEST"ccccc

I tried sed and (awk -F[\"]) but could not get some useful results. How can this be done ?

Update: I made the sample clearer..

There are 3 different types:...:

1: Delete from "MyPorts" to }},
2. Delete "Proto to \"
3. Delete from " PROTO" till one character before \", only if left from Proto is a space 

Update 2: How can this be done if the sample data is also in one line, like this:

aaaa"MyPorts":{"80/tcp":{},"8080/tcp":{},"9080/tcp":{},"9090/tcp":{}},aaaabbbb"PROTO 9080/tcp 9090/tcp"bbbbbcccc"TEST PROTO 80 8080"ccccc

After using the replace it should look like:

aaaaaaaabbbbbbbbbcccc"TEST"ccccc
  • 2
    this line ccccPROTO 80 8080"ccccc looks strange. How diverse could be your lines? How this line AaaA"aaa:1"cc"aaa"bbb"{}"aaA should be treated? – RomanPerekhrest Jun 14 '18 at 18:02
  • I updated the sample to make it clearer.. There are 3 different types:...: 1: Delete from "MyPorts" to }}, 2. Delete "Proto to \" . 3 Delete from " PROTO" till \", only if left from Proto is a space – biohell Jun 14 '18 at 19:59
1

sed approach:

sed -E 's~("MyPorts.*\},|"PROTO[^"]+"| +PROTO[^"]+)~~' file

The output:

aaaaaaaa  
bbbbbbbbb
cccc"TEST"ccccc

Bonus approach for one-line string input:

$ s='aaaa"MyPorts":{"80/tcp":{},"8080/tcp":{},"9080/tcp":{},"9090/tcp":{}},aaaabbbb"PROTO 9080/tcp 9090/tcp"bbbbbcccc"TES^CPROTO 80 8080"ccccc'

$ sed -En 's~("MyPorts.+\},|"PROTO[^"]+"| +PROTO[^"]+)~~gp' <<<"$s"
aaaaaaaabbbbbbbbbcccc"TEST"ccccc
  • Thank you very much. Works like a charm !!! Great and Short Solution.. Cannot mark this a solution due less reputation, Thanks RomanPerekhrest found it. – biohell Jun 14 '18 at 20:28
  • Great job at interpreting the OP's request! @biohell can accept the answer, no minimum reputation is required. – simlev Jun 14 '18 at 20:58
  • @RomanPerekhrest: if the sample data is in one line,your call doesn't work.. Can you chnage your call to reflect this ? – biohell Jun 15 '18 at 9:40
  • @biohell, all additional cases should be described in the question (with respective input fragment) – RomanPerekhrest Jun 15 '18 at 9:44
  • @@RomanPerekhrest: i updated the question. – biohell Jun 15 '18 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.