Search code examples
htmlbashtype-conversion

How to convert text to html character codes with a bash script?


I tried recode:

echo '>' | recode ascii..html
>

But it only seems to convert characters like > < and ":

echo 'a' | recode ascii..html
a

I want to convert letters and other characters too. I.e, the desired output of the above command is &#97;.

Is there any simple way to do this without creating some big regular expression?


Solution

  • You can use printf to get ascii value of characters using ' in front of the variable. This will of course result in &#62; instead of &gt;. You can use the code bellow to convert $1 to a string of html ascii codes.

    str=$1
    for (( i=0; i<${#str}; i++ )); do
      c=${str:$i:1}
      printf "&#%d;" "'$c" #
    done
    echo ""