开发者

Perl one-liner with single quote

开发者 https://www.devze.com 2023-02-13 09:08 出处:网络
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.

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"
开发者_StackOverflow中文版

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


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'


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 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消