Reputation: 817
Forgive me if this is a trivial question, I don't have much experience with this.
I have a file that looks like this:
{text},
{text},
{text},
{text},
I want it to look like this
[{text},
{text},
{text},
{text}]
Note that the final comma is removed, and that there are now square brackets at the beginning and end of the file.
So, I have thousands of files in a directory, and each file has to be fixed to do that.
I'm guessing I have to use sed somehow but I don't really know how to make it happen and don't want to do it manually using VIM since there are so many files...
EDIT:
I tried to use:
sed -i '1s/^/\[/;$s/,$/\]/' *
as suggested by codeforester. I get an error saying "Argument list too long"...
Upvotes: 2
Views: 3088
Reputation: 158110
I would remove the existing comma at the end of the lines with sed
and then use jq
to build the json array:
sed 's/,$//' file | jq -s .
To run this over many files, I recommend to create a little shell script:
fix-json.sh
#!/bin/bash
file="${1}"
sed 's/,$//' "${file}" | jq -s . > "${file}.tmp"
if [ ${PIPESTATUS[1]} != 0 ] ; then
echo "${file} is broken"
rm "${file}.tmp"
else
mv "${file}.tmp" "${file}"
fi
Now use find
to run the above script on the input files:
chmod +x fix-json.sh
find /path/to/files -type f -name '*.json' -exec ./fix-json.sh {} \;
Upvotes: 4