Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# by Martin Wermers[1], 2018
# Written for my answer on the StackOverflow question 'Include another HTML file in a HTML file':
# This work is licensed under a Creative Commons Attribution-ShareAlike 4.0
# International License. See .
# Credits to Greg Minshall[2] for the improved sed command that also escapes
# back slashes and single quotes, which my original sed command did not
# consider.
# [1]
# [2]
# Checking correct number of arguments
if [[ "$#" == 0 ]]; then
echo 'Please enter the filename of the HTML file that should be escaped for insertion via JavaScript.'
exit 1
if [[ "$#" > 1 ]]; then
echo 'Too many arguments. Please pass only one filename at a time.'
exit 1
# Checking for existance of entered file
if [[ ! -f $1 ]]; then
echo "WARNING! The file you have entered does not exist!"
exit 1
filename=$(basename "$1")
echo "document.write('\\" > $targetFile
sed 's/\\/\\\\/g;s/^.*$/&\\/g;s/'\''/\\'\''/g' $1 >> $targetFile
echo "');" >> $targetFile
echo "The file '$1' was converted into '$targetFile'."
echo "To include it in another HTML file, just enter the following line at the desired position for insertion:"
echo ""
echo " <script src=\"$targetFile\"></script>"
echo ""
exit 0

This comment has been minimized.

Copy link

@lucidBrot lucidBrot commented Aug 12, 2018

Thanks for this! Note that this script escaped the last closing quote though. I suggest changing line 41 to echo "n');" or manually removing the last backslash in the generated js file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment