问题
I created a script that is generating HTML code. At the end of the script, I need to hightlight some words in a table by making them bold.
So I need to replace in the code, every instance of WORD by WORD or WORD
of course, WORD is stored in a variable $CODE to make this much more harder.
I tryed to used the sed command unfortunatelly with no success.
sed -e 's/$CODE/<b>$CODE</b>/g' page.html > newpage.html
I tryed also with double quotes, with escape chars before the /, many combination of quotes and double quotes, with | as delimiter, always with no success. If any one of you could point me to a solution, I would be really greatfull.
PS : Tryed also with awk ... but with variable it's a real pain in the ...
EDIT : Here is my exact code to help all of you. code_list.txt contain a list of CODE-description lines.
for y in code_list.txt
do
CODE=$(echo $y | cut -f1 -d-)
awk -v code="$CODE" '{if(match($0,code)){gsub(code,"<b>"code"</b>")}} 1' $SCRIPTS/html/daily_running_jobs.html > $SCRIPTS/html/daily_running_jobs_highlight.html
mv $SCRIPTS/html/daily_running_jobs_highlight.html $SCRIPTS/html/daily_running_jobs.html
done
B²
回答1:
There is no reason your idea would not work if
you use " instead of '
there is no
@
(EDIT: and no linebreak) in the $CODE expression (replace/
by@
)
sed -e "s@$CODE@<b>$CODE</b>@g" page.html > newpage.html
The problem with your solution was the quoting, and that the sed regex separator /
was also used in your replacement expression as in </b>
EDIT - multiple values to be replaced from file
If you have a file code_list.txt where all strings-to-be-replaced are in one-per-line, do
cp page.html newpage.html
while read var
do
mv newpage.html newpage1.html
sed -e "s@$var@<b>$var</b>@g" newpage1.html > newpage.html
# optionally rm newpage1.html
done < code_list.txt
回答2:
awk -vcode="$CODE" '{if(match($0,code)){gsub(code,"<b>"code"</b>")}} 1' page.html > newpage.html
assume there is a variable $CODE
We pass it to awk variable, if there is a match then replace
来源:https://stackoverflow.com/questions/37632171/sed-in-aix-script-do-not-work-with-special-chars