Abhishek
Abhishek

Reputation: 35

Delete lines above and below a string from json file

I have a my_file.json file, which contains invalid json as below, and i need to delete the lines starting from "{" upto "}," if the "name": my_script.py.

[
            {
                "use":                     abcd   
                "name":                    my_script.py
                "contact":                 xyz
                "time":                    11:22:33
             },
            {
                "use":                     abcd   
                "name":                    some_other_script.py
                "contact":                 xyz
                "time":                    11:22:33
             },
            {
                "use":                     abcd   
                "name":                    my_script.py
                "contact":                 xyz
                "time":                    11:22:33
             }
]

I tried below sed,

sed '//{/ {:a;/}/!{N;ba};/my_script/d}' my_file.json

but it is not working and giving me error

"sed: -e expression#1, char 11: `}' doesn't want any addresses".

Upvotes: 0

Views: 93

Answers (1)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed '/{/{:a;N;/}/!ba;/my_script\.py/d}' file

Gather up the lines between { and } and if those lines contain my_script.py delete them.

The current example is not json, however this is probably a more robust solution:

sed 's/\S\+/"&"/2;T;N;/}/!s/\n/,&/;P;D' file |
jq '[ .[]|select(.name!="my_script.py") ]'

Upvotes: 4

Related Questions