Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash print escaped file contents

Tags:

bash

printf

cat

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.

like image 424
Petr Petrov Avatar asked Jul 08 '16 18:07

Petr Petrov


Video Answer


2 Answers

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)"
like image 56
Charles Duffy Avatar answered Sep 18 '22 11:09

Charles Duffy


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.

like image 26
that other guy Avatar answered Sep 21 '22 11:09

that other guy