How to extract a string enclosed in single quotes in perl?

How to extract abc from 'abc' using perl regex?

I tried

echo "'abc'" | perl -ne 'if(/\'(.*)\'/) {print $1}' 

but it shows - bash: syntax error near unexpected token `('

Thanks in advance for your reply.

+4
source share
6 answers

This is not a perl problem, this is a shell problem: you cannot include single quotes in single quotes.

You must replace each individual quote with '\'' (end of single quotes, escaped single quote, start of quotes with signature)

 echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}' 
+7
source

Well, a cheap way is not to surround your perl statement with single quotes:

 echo "'abc'" | perl -ne "if(/'(.*)'/) {print $1}" 

Shell shielding has odd rules ...

If you really want to do this in the โ€œrightโ€ way, you can end your first single quote, put a quote, and run another:

 echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}' 
+2
source

choroba answer solves the exact problem. For a generic solution to any citation problem, use String :: ShellQuote :

  $ alias shellquote='perl -E'\'' use String::ShellQuote qw(shell_quote); local $/ = undef; say shell_quote <>; '\''' $ shellquote user input โ†’ if(/'(.*)'/) {print $1}โ„ perl output โ†’ 'if(/'\''(.*)'\''/) {print $1}' 
+2
source

Before using an alternative citation method , select one of the dollar-sign Perl codes to direct bash, which disables shell extension

 echo "'abc'" | perl -ne $'if(/\'(.*)\'/) {print $1}' 
+2
source

you need to avoid single qoute with '\' '

echo "'abc'" | perl -ne 'if( /'\''(.*)'\''/ ){print $1}'

+1
source

You have a problem quoting the shell, not a problem with Perl.

This is useful for sed :

 echo "'abc'" | sed "s/'//g" 
+1
source

Source: https://habr.com/ru/post/1389318/


All Articles