It’s not really append what I’m looking for but because I had future noobs in mind, I took the liberty of including it in the title.
I am looking to search for/capture a line-ending "
and a ]
in the next line (end of file) in json files (many of them). I am using multiline option in ripgrep and forwarding the list of results to be replaced with sed. Running a sole rg without -l lists my results without problems. The problem is with the sed part.
cd path/to/folder
rg -l --multiline '(")(n])' regex/to/path/to/folders/settings.json | xargs sed -i 's/(")(n])/1,nInputStringn2/' *.json
- I am searching recursively in multiple folders (the regex is correct as I used it for other replacements including git).
What I want is to put a comma after the comma-less line (with the captured quote at the end), put in a new line, put in a string (I’ll handle the spaces and quotes myself), another new line and a ]
to close the json settings files.
Sample:
[
"data1",
"data2",
"data(n)"
]
Desired result:
[
"data1",
"data2",
"data(n)",
"inputstring"
]
No matter how I tried, I couldn’t make it work. The *.json
at the end is probably superfluous, just as the brackets in the rg command part. But these are not the problem. What is the problem? Am I missing a sed option/flag? Is there some character that needs to be escaped? Maybe the syntax with the groups in the replacements?
3
Answers
Solution to my case based on the kind answers. I couldn't use
sponge
command and was usingfind
this time:With the proper tool:
jq
:To edit in place:
You can use
+=
to update the array. Also, use--arg
to import a string from outside jq.