I try to create a short perl
command that creates SQL inserts for my DB based on a text file. However, I am not able to get in the single-quotes used by SQL
perl -pe '$i += 1; chomp; @a = split /\t/; $_ = "INSERT INTO XYZ VALUES($i, \'$a[4]\');\n"'
results in a syntax error near unexpected token `)'
Any ideas?
You need to escape them for the shell, not for Perl. This requires a slightly different syntax. Assuming you're running this under bash, ksh, or similar, then
should print
greengrocer's
.Alternatively, you could insert the character as a hex escape sequence:
Use the technique @Porculus suggested in his answer:
This closes the single-quoted string just before the single quote, then uses an escaped single-quote, then opens a new single-quoted string.
The beauty of this technique is that you can automate it:
resulting a properly-quoted string you can paste on to the command line :
Or you can make a shell-script for it:
(The above sed firstly replaces each
'
with'\''
then puts a'
at the front and back.perl -pe "\$i += 1; chomp; @a = split /\t/; \$_ = \"INSERT INTO XYZ VALUES(\$i, '\$a[4]');\n\""
From this page it states for BASH: "A single quote may not occur between single quotes, even when preceded by a backslash.". So use double quotes instead and escape as necessary.
Found a work-around by using a | for all single-quote and then in a second perl call replacing this | by a single quote (
perl -pe "s/\|/'/g"
)Still interested in a better solution.