LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   In a string how to add backslash "\" before apostrophe (https://www.linuxquestions.org/questions/linux-newbie-8/in-a-string-how-to-add-backslash-%5C-before-apostrophe-4175579612/)

karthika.s 05-12-2016 08:57 AM

In a string how to add backslash "\" before apostrophe
 
Iam creating a shell script that have a variable with apostrophe. Want to add backslash before the variable like "St Antony\'s company" and give this variable in the WHERE condition of a sql query.

My script

Var1="St Antony's company"

if [[ "$Var1" =~ \' ]]
then
Var1= `echo $Var1 | sed s/\'/\\\\\'/g`
echo $Var1
fi

echo -n "SELECT field1, field2 FROM table1 WHERE field3='$VAR'";

but it is not working. Please help me

keefaz 05-12-2016 09:10 AM

Use double quotes around sed command
Code:

sed "s/'/\\\'/g"
Maybe prepared statements could be a nice option though (protect against sql injection also)

Turbocapitalist 05-12-2016 09:15 AM

Quote:

Originally Posted by keefaz (Post 5544389)
Maybe prepared statements could be a nice option though (protect against sql injection also)

Prepared statements help with a lot, especially against injection attacks.

grail 05-12-2016 10:09 AM

If using bash you could just do the change in place:
Code:

Var1="St Antony's company"

echo -n "SELECT field1, field2 FROM table1 WHERE field3='${VAR//\'/\\\'}'";



All times are GMT -5. The time now is 02:46 PM.