how to convert text file to json string (replace newlines with "\n")

Instead of echo, you could use the jq JSON parsing tool:

jq -r . < file.js > file.txt

It would also have the advantage of removing the enclosing ", and turning the \" into ".

To convert back to a JSON string:

jq -Rs . < file.txt > newfile.js

For the more generic question about converting newlines to \n, you can use perl:

perl -pe 's/\n/\\n/'

The difference with sed 's/\n/\\n/' which wouldn't work is that perl includes the trailing newline in the record that s operates on, but not sed.


There is a solution in the stackoverflow.

Here you would use:

sed -E ':a;N;$!ba;s/\r{0,1}\n/\\n/g' file.txt > value.js