I have following text in a file

 "rules": [
    "rulesReference": [
            "link": "https://localhost/mgmt/tm/ltm/rule/~Common~Tetration_TCP_L4_ipfix?ver=12.0.0"

want to extract anything inside "rules": [] currently it is


Output should look like


but again this can be anything.


If your input file contains non full-fledged JSON but only inner fragment (though structurally valid) you may recover the missing "outer" parts to get a full valid JSON structure.

sed + jq solution:

jq -r '.rules[] | sub("/Common/"; "")' <(sed '1 s/^/{/; $ s/$/]}/' file)

The output:


Of course, if in real you have a valid JSON - just skip the sed processing and just use:

jq -r '.rules[] | sub("/Common/"; "")' file

If this is a well-formed JSON file:

$ jq -r '..|select(type=="object" and has("rules")).rules|map(split("/")|.[-1])|.[]' file.json

This will use jq to recursively find all the JSON objects that has a rules key. For all the array values of those keys, it will split the value on / and return the last component of it.


Using AWK:

awk -F '[/"]' '/"rules": /,/],/{if(/"rules": |],/) next; print $(NF-1)}' file.txt

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.