Issue
I am trying to write a bash script that generates uuids and writes that to a file, in a json array format. I have written a simple code that generates the id and writes to a file but the issues i am running into are;
here is my own implementation
function uud {
for ((i=1;i<=$1;i++));
do
echo "\`uuidgen\`", >> $file
done
}
for file in file1.json file2.json;
do
$( uud $1)
done
- I am having issues with converting the ids into strings.
- Converting the results to arrays.
Currently my solution prints the ids into the file in this format
caca8fef-42d6-4b21-9d6b-0e40d348bd53,
e6e12fb5-4304-4ba9-b895-931bb4b58fbf,
df699ecd-d887-413e-8383-2a98ac2fa22f,
and this is what i want to acheive, How can I go about getting this result?
[
"caca8fef-42d6-4b21-9d6b-0e40d348bd53",
"e6e12fb5-4304-4ba9-b895-931bb4b58fbf",
"df699ecd-d887-413e-8383-2a98ac2fa22f"
]
Solution
Use jq
to generate the JSON.
uud () {
for ((i=0; i< $1; i++)); do
uuidgen
done
}
for file in file1.json file2.json; do
uud 5 | jq -Rs 'rtrimstr("\n") | split("\n")' > "$file"
done
-Rs
reads the entire input into a single JSON string, which you then split (after removing the trailing newline) on newlines to produce the desired array.
One blogger suggests using two jq
processes, which is more expensive but arguably simpler:
for file in file1.json file2.json; do
uud | jq -R . | jq -s . > "$file"
done
Answered By - chepner Answer Checked By - Candace Johnson (WPSolving Volunteer)