Naba Chinde Naba Chinde - 4 months ago 27
JSON Question

Find and edit a Json file using bash

I have multiple files in the following format with different categories like:

{
"id": 1,
"flags": ["a", "b", "c"],
"name": "test",
"category": "video",
"notes": ""
}


Now I want to append all the files flags whose category is
video
with string
d
. So my final file should look like the file below:

{
"id": 1,
"flags": ["a", "b", "c", "d"],
"name": "test",
"category": "video",
"notes": ""
}


Now using the following command I am able to find files of my interest, but now I want to work with editing part which I an unable to find as there are 100's of file to edit manually, e.g.

find . - name * | xargs grep "\"category\": \"video\"" | awk '{print $1}' | sed 's/://g'

sps sps
Answer

You can do this

find . -type f | xargs grep -l '"category": "video"' | xargs  sed -i -e '/flags/ s/]/, "d"]/'

This will find all the filnames which contain line with "category": "video", and then add the "d" flag.

Details:

find . -type f 

=> Will get all the filenames in your directory

xargs grep -l '"category": "video"'

=> Will get those filenames which contain the line "category": "video"

xargs  sed -i -e '/flags/ s/]/, "d"]/'

=> Will add the "d" letter to the flags:line.

Comments