In REXX


/* ********************************************************************** */
/* The Bourne shell treats some characters in a command's argument list as*/
/* having a special meaning.  This could result in the shell executing    */
/* unwanted commands. This code escapes the special characters by         */
/* prefixing them with the \ character.                                   */
/* ********************************************************************** */
Esc=';&|><*?`$(){}[]!#' /*List of chars to be escaped*/

DO UNTIL Esc=''/*Check for chars to be escaped*/
  PARSE VAR Esc Char 2 Esc
  P=POS(Char,Str)   
  DO WHILE P /=0
     Pre=SUBSTR(Str,1,P-1) /*Get text before char*/
     Post=SUBSTR(Str,P+1)  /*and after    */
     Str=Pre||'\'||Char||Post
     P=POS(Code,Str)
  END /*DO WHILE P/= 0*/
END /*DO UNTIL Esc='' */ 

In Perl

To escape metacharacters rather than just detecting them, a Perl subroutine like this could be used:

  sub esc_chars {
  # will change, for example, a!!a to a\!\!a
     @_ =~ s/([;<>\*\|`&\$!#\(\)\[\]\{\}:'"])/\\$1/g;
     return @_;
  }