I'm trying to print the file contents with escaped double quotes.
# read file contents from ${filename}
# - escape double quotes
# - represent newlines as '\n'
# print the result
echo "my file contents: \"${out}\""
So for example if my file is
<empty line>
console.log("hello, world");
<empty line>
it should print
my file contents: "\nconsole.log(\"hello, world\");\n"
I was trying to use printf with %q format specifier, but had problems that it removes the trailing spaces.
To do only the two literal transforms you've explicitly asked for:
IFS= read -r -d '' content <file
content=${content//'"'/'\"'/}
content=${content//$'\n'/'\n'}
echo "file contents: $content"
That said, if you're trying to represent arbitrary content as JSON strings, let a fully compliant JSON parser/generator do the heavy lifting:
IFS= read -r -d '' content <file
echo "file contents: $(jq -n --arg content "$content" '$content')"
...or, even better (to support even files with contents that bash can't store as a string), let jq
read from the input file directly:
echo "file contents: $(jq -Rs . <file)"
Command substitutions strip trailing line feeds. You can prevent this by adding a dummy non-linefeed character and then stripping it:
printf '\n\nfoo\n\n' > file
contents="$(cat "file"; printf x)"
contents="${contents%x}"
printf "The shell equivalent of the file contents is: %q\n" "$contents"
If you are trying to generate JSON, you should instead be using jq
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With