Function to add escape character before specified character

Hi ,

I am looking for a function which will do the following.

  1. I have a variable which will hold few special chracter like
SPECIAL_CHARS="& ;"
  1. I have an escape character.
ESCAPE_CHAR="\"
  1. Now when I passed some string in the function it will return the same string but now it will have the escape character before all the special characters.
Example:
Input: abcd fkaj&dsdsd
Output: abcd fkaj\&dsdsd
# echo "abcd fkaj&dsdsd" | ruby -e 's=gets; puts s.gsub(/([& ;])\1*/,"\\\\\\1")'
abcd\ fkaj\&dsdsd
1 Like

Python re module maybe handy for that task:

echo "abcd fkaj&dsdsd;"|python -c 'import re;import sys;print re.escape(sys.stdin.read().strip()),'
1 Like

Awk :

$ echo "abcd fkaj&dsdsd" | awk 'gsub(/[[:punct:]]|[[:space:]]/,"\\\\&")'
abcd\ fkaj\&dsdsd
1 Like

Another approach:

SPECIAL_CHARS='& ;'
ESCAPE_CHAR='\'
echo 'abcd fkaj&dsdsd' | awk -v SC="$SPECIAL_CHARS" -v EC="$ESCAPE_CHAR" '
        BEGIN {
                n = split ( SC, A )
        }
        {
                for ( i = 1; i <= n; i++ )
                        gsub ( A, EC "\\&", $0 )
                print
        }
'
1 Like

Try also

awk -v X="& ;" -v E='\' '{gsub(/./,"&|",X); sub (/.$/,"", X); gsub (X, "\\" E "&")}1' <<< 'abcd fkaj&dsdsd'
abcd\ fkaj\&dsdsd

If you know the escape char is back slash, this may work:

awk -v X="& ;" -v E='\' '{gsub(/./,"&|",X); sub (/.$/,"", X); gsub (X, E E "&")}1' <<< 'abcd fkaj&dsdsd'
abcd\ fkaj\&dsdsd

Yoda's approach misses the space special char as that is used as a separator by the split function.

EDIT: Even simpler:

awk -v X="& ;" -v E='\' '{ gsub ("["X"]", E E "&")}1' <<< 'abcd fkaj&dsdsd'
abcd\ fkaj\&dsdsd
1 Like

I don't think OP want blank space to be escaped. I don't see blank space escaped in OP's expected output.

I guess OP want to escape only those characters defined in variable SPECIAL_CHARS

1 Like

@ Yoda and RudiC

Actually I am confused about post1's example , whether example output is expected output / error in output / escape char missing output ?

1 Like

Thank you all.

---------- Post updated at 05:09 PM ---------- Previous update was at 05:08 PM ----------

My Bad. I used space as delimited for those special character.