Search code examples
perlshellquoting

Perl one-liner with single quote


I 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 the first field 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 issue.

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"

How can we use single and double quotes in Perl one-liners?


Solution

  • 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'