Perl one-liner with single quote

2020-06-04 04:16发布

问题:

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?

回答1:

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'


回答2:

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.



回答3:

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.



回答4:

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.