Extracting information from a string using regex in bash

前端 未结 2 1130
眼角桃花
眼角桃花 2021-01-28 12:13

I have a string variable in bash which looks like so:

{\"SOGoTimeFormat\": \"%H:%M\", \"SOGoMailShowSubscribedFoldersOnly\": \"0\", \"SOGoMailSignaturePlacement\         


        
相关标签:
2条回答
  • 2021-01-28 12:57

    jq is an excellent tool for parsing and editing JSON, easy to drive from shell.

    # extract "enabled" field from "Forward"
    enabled=$(jq '.Forward.enabled` <input.json)
    

    ...or, to do the whole thing in one pass:

    jq '
      if .Forward.enabled==1 then
        .Forward.forwardAddress=[(
          .Forward.forwardAddress[] |
          select(. | test("testuser2") | not)
        )]
      else . end
    ' <input.json >output.json
    
    0 讨论(0)
  • 2021-01-28 12:58

    What you have is JSON and what you should be using is a JSON parser. Using regex is not a good substitute.

    Here's some python that loads the string, and if enabled in Forward is 1, deletes any address with the substring "testuser2" from the forwardAddress list:

    #!/bin/python
    import sys
    import json
    
    thing = json.load(sys.stdin)
    forward = thing["Forward"]
    
    if forward["enabled"] == 1:
        forward["forwardAddress"] = \
            filter(lambda x: not "testuser2" in x, \
                forward["forwardAddress"])
    
    json.dump(thing, sys.stdout)
    

    You can run it with

    echo "$yourvariable" | python thisfile.py
    

    The json re-encoding process might shuffle the fields. This doesn't matter, as the strings still represent the same json objects.

    0 讨论(0)
提交回复
热议问题