How to convert to HTML code?

The perl CGI module has a escapeHTML function that makes it pretty easy:

perl -e 'use CGI qw(escapeHTML); print escapeHTML("<hi>\n");'

Or to do an entire file:

perl -p -e 'BEGIN { use CGI qw(escapeHTML); } $_ = escapeHTML($_);'  FILENAME

The recode utility supports HTML as one of the encodings. (You can even specify an HTML version.) In the text-to-entities direction, it will also recode non-ASCII characters into entities; you need to specify the correct input encoding (e.g. ASCII, latin1, utf-8, …).

recode utf8:html <input-file.txt >output-file.txt
recode l1..html file-to-recode.txt