Use perl to replace html string

# Single quote to encapse a fixed string
export old_string='<h1>List of fruits</h1><table class=\"relative-table wrapped\"><colgroup><col style=\"width: 32.7513%;\" /><col style=\"width: 19.6693%;\" /><col style=\"width: 15.3365%;\" /><col style=\"width: 19.5826%;\" /><col style=\"width: 12.6502%;\" /></colgroup><tbody><tr><th class=\"highlight-#abf5d1\" data-highlight-colour=\"#abf5d1\" style=\"text-align: left;\">Fruit name</th><th class=\"highlight-#abf5d1\" colspan=\"1\" data-highlight-colour=\"#abf5d1\">Other names</th><th class=\"highlight-#abf5d1\" data-highlight-colour=\"#abf5d1\" style=\"text-align: left;\">Date</th><th class=\"highlight-#abf5d1\" colspan=\"1\" data-highlight-colour=\"#abf5d1\">Color</th><th class=\"highlight-#abf5d1\" colspan=\"1\" data-highlight-colour=\"#abf5d1\">Note</th></tr>'

export NAME="Banana"
export NOTE="yummy"

# Tripple quotes to encapse variables
export append_string="""<tr><td colspan=\"1\"><p class=\"Default\"><span><a href=\"http://localhost/${NAME}/\">${NAME}</a></span></p></td><td colspan=\"1\"></td><td colspan=\"1\">${NAME}</td><td colspan=\"1\"><p><a href=\"http://localhost/${NAME}/${NAME}\">N/A</a></p></td><td colspan=\"1\"><strong><a href=\"http://localhost/${NOTE}\">${NOTE}</a></strong></td></tr>"""

export new_string=${old_string}${append_string}

perl -i.bak -pe 's/\Q$ENV{old_string}\E/$1$ENV{new_string}$2/' mypage.html

# -i.bak to make a backup of mypage.html
# -pe option allows you to run Perl code (pattern matching and replacement in this case) and display output from the command line
# \Q quote (disable) pattern metacharacters until \E
# \E end either case modification or quoted section, think vi
# $ENV replacing code with shell variables

Ref https://stackoverflow.com/a/2924104/691530

Loading