Perl one-liner with single quote

sfgroups picture sfgroups · Feb 24, 2011 · Viewed 12.8k times · Source

I was use a Perl one-liner to create an SQL statement, but I am not able to include single quotes.

This is what I want: Take first filed and add quotes to it.

echo "a,b" | perl -F',' -lane 'print $F[0];'
 'a'

I tried a few different ways, but it didn't work for me.

1.

echo "a,b" | perl -F',' -lane 'print qq('$F[0]');'
[0]

2.

echo "a,b" | perl -F',' -lane 'print q('$F[0]');'
[0]

Here is another interesting.

It is printing a single quote with the print statement, but if I assign a value to the variable and print it's not working.

perl -lwe "print q( i'am );"
 i'am

perl -lwe "$b=q( didn't ); print $b"

Can you help me to understand how can we use single and double quotes in Perl one-liners?

Answer

dogbane picture dogbane · Feb 24, 2011

You can't use single quotes alone. You need to escape them correctly using '\'' This works:

$ echo "a,b" | perl -F',' -lane 'print "'\''$F[0]'\''";'
'a'