0

I’m using bash shell with Perl v 5.18.2. I’m running this statement

perl -pi -e "s/([^,]+),([^,]+),([^,]+),(.*[^\n]+)\n/select '\$1', u.id, u.first_Name, u.last_name, u.url FROM user u, user_role ur where u.id = ur.user_id and lower(ur.role_id) = '\$2' and lower(u.first_name) = lower('\$3') and lower(u.last_name) = lower('\$4');/g" /tmp/users.csv 

But what I want to do is somehow before the “$3” and “$4” arguments are placed into the replace section of this perl statement, I want to escape any single quotes that might appear in them so that the SQL statements run properly (this will run on MySQL 5.5.18). How do I adjust the above so that when perl replaces the $3 and $4 arguments it replaces single quotes with escaped MySQL singe quotes?

Dave
  • 15,639
  • 133
  • 442
  • 830
  • 2
    "I want to escape any single quotes that might appear in them so that the SQL statements run properly" That way lies madness. Use [DBI](https://metacpan.org/pod/DBI) and [placeholders](https://metacpan.org/pod/DBI#Placeholders-and-Bind-Values). – ThisSuitIsBlackNot Aug 29 '16 at 16:28
  • Ok, so how do you do that? – Dave Aug 29 '16 at 16:46

1 Answers1

-1
perl -pi -e "sub R{(\$a=shift)=~s/'/''/g;\$a;} s/([^,]+),([^,]+),([^,]+),(.*[^\n]+)\n/select '\$1', u.id, u.first_Name, u.last_name, u.url FROM user u, user_role ur where u.id = ur.user_id and lower(ur.role_id) = '\$2' and lower(u.first_name) = lower('@{[R(\$3)]}') and lower(u.last_name) = lower('@{[R(\$4)]}');/g;" /tmp/users.csv

Perl transposes any string (including regular expression). And execute any code enclosed in @{[ code ]}.

Create function (R()) for escaping MySQL string and call it from replacement string as @{[ R($3) ]}.

Mike
  • 1,985
  • 1
  • 8
  • 14