Hi ,
I am looking for a function which will do the following.
I have a variable which will hold few special chracter like
SPECIAL_CHARS="& ;"
I have an escape character.
ESCAPE_CHAR="\"
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
kurumi
December 30, 2013, 3:00am
2
# echo "abcd fkaj&dsdsd" | ruby -e 's=gets; puts s.gsub(/([& ;])\1*/,"\\\\\\1")'
abcd\ fkaj\&dsdsd
1 Like
Klashxx
December 30, 2013, 3:11am
3
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
Yoda
December 30, 2013, 12:05pm
5
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
RudiC
December 30, 2013, 12:33pm
6
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
Yoda
December 30, 2013, 1:00pm
7
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
anupam_halder:
Hi ,
I am looking for a function which will do the following.
I have a variable which will hold few special chracter like
SPECIAL_CHARS="& ;" ---> Looks like space is also considered in variable
I have an escape character.
ESCAPE_CHAR="\"
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
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.