Jimnotgym
Jimnotgym

Reputation: 115

Bash string operations unwanted remove new line characters

I'm completely new to bash scripting so excuse me.... I am trying to combine some html content with a template that contains standard headings, the template has a place-holder "REPLACEME" which I thought I could just find and replace on. The loop simply repeats the operation on all the files in the directory.

REPLACEME="REPLACEME"
for file in *.html
do
TEMPLATE=$(<../template/template.html)
CONTENT=$(<$file)
OUTPUT="${TEMPLATE/"$REPLACEME"/"$CONTENT"}"
echo $OUTPUT > ../compiled/$file
done

This works but the resulting html file has been stripped of new line characters, which makes it look like junk! Can anyone help?

Upvotes: 1

Views: 226

Answers (2)

sjsam
sjsam

Reputation: 21965

Using sed you could achieve it like below :

sed -i 's/REPLACEME/new_text/g' /path/to/your/template.html

The -i option in sed is for inplace edit & the g option is for global substitution.

Edit 1:

If you need to use a variable inside sed you can do it this way

var="Sometext";
sed -i "s/REPLACEME/$var/g" /path/to/your/template.html

Mind the double quotes here, it makes the shell expand variables.


If your system supports gnu-awk (gawk) you may achieve the above with

gawk '
{
$0=gensub(/REPLACEME/"NEWTEXT","g",$0)
printf "%s\n", $0
}' < /path/to/your/template.html > newtemplate.html && mv newtemplate.html template.html

Upvotes: 3

John1024
John1024

Reputation: 113964

Replace:

echo $OUTPUT > ../compiled/$file

With:

echo "$OUTPUT" > ../compiled/$file

The shell performs word splitting on unquoted variables. With the default value for IFS, this means that all sequences of whitespace, which includes tabs and newlines, are replaced with a single blank. To prevent that, put the variable in double-quotes as shown above.

Upvotes: 3

Related Questions