Pergunta

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?

Foi útil?

Solução

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'

Outras dicas

You need to learn how your shell treats quotes.
I would just use the ASCII value for ':

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

q// and qq// operators can also be useful in one-liners.

Use a variable with the octal value:

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

Also, a slight modification of your attempt #1 would work:

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

That uses double quotes for the outer set and escapes the dollar sign to prevent the shell from interpreting it.

Placing the script in in double quotes rather than single quotes will allow you to use single quotes inside the script without having to escape or use ANSI sequences to represent the single quote. This is likely the most effective and easily-readable solution.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top