Bash string operations unwanted remove new line characters

a 夏天 提交于 2019-12-24 13:51:02

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/36993842/bash-string-operations-unwanted-remove-new-line-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!