Wednesday, December 29, 2021

[SOLVED] sed / grep / awk : match a json object in a txt

Issue

I need to extract a json from a console output that looks like that :

[main] Lin of log 1
[main] Lin of log 2
...
[main] Lin of log n
{
    "jsonProperty1": "aString",
    "jsonNestedObject1": {
        ...
    },
    ...
    "jsonPropertyN": "something"
}
[main] Lin of log n+1
...
[main] Lin of log m

I want to write this JSON object in an "input.json" file, how can I do this using commands like awk, grep or sed please ?

Thank you in advance for your help


Solution

Please try the following:

awk '/^{$/{f=1}f{print; if(/^\}$/) f=0}' input > input.json

Explanation: When { is found, f is set. With f true lines are printed, but if } is found, f is unset, and printing stops. For further reading, please check out Is a /start/,/end/ range expression ever useful in awk?



Answered By - Thomas Hansen