Paste data into a file as an array in bash

With the following command, I write data to file.txt.

node scripts/js/script.js /home/desktop/my-file.mp3 > file.txt

Content file.txt:

0
0
0
0
0
0.00003051850947599719
0
-0.00003051850947599719
0
0.00006103701895199438
0

What should be the way to write data as an array? Like this:

[0, 0, 0, 0, 0.00003051850947599719, 0, -0.00003051850947599719, 0, 0.00006103701895199438, 0]

Thanks in advance.

+4
source share
3 answers

I will assume that you cannot change scripts/js/script.jsand therefore show you a script that takes an intermediate step between your node script and the output file:

One way is to use the following GNU sed script:

node ... | sed 's/"/\\"/;s/$/,/;1s/^/[/;$s/,$/]/' > file.txt

If you do not want to keep newlines, you can use tr:

node ... | sed 's/"/\\"/;s/$/,/;1s/^/[/;$s/,$/]/' | tr -d '\n' > file.txt
+1
source

Here, use JSON.stringify():

var fs = require('fs');
var arr = [0, 0, 0, 0, 0.00003051850947599719, 0, -0.00003051850947599719, 0, 0.00006103701895199438, 0];

fs.writeFile('file.txt', JSON.stringify(arr), function (err) {
  if (err) return console.log(err);
});
+1
source

This solves your problem:

content=( `cat "file.txt" `)

for i in "${content[@]}"
do
    echo $i
done
0
source

All Articles