简体   繁体   中英

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

How do I extract abc from 'abc' using perl regular expression?

I tried

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

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

Thanks in advance for your reply.

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

You have to replace each single quote with '\\'' (end of single quotes, escaped single quote, start of signle quotes)

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

在带有美元符号的单引号Perl代码之前,指示bash使用替代引用方法来关闭shell扩展:

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

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

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

Shell escaping has odd rules...

If you really want to do it the "right" way you can end your first single quoted string, put the quote in, and start another one:

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

choroba's answer solves the exact problem. For a generalised solution to any quoting 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}'

你需要用'\\''来逃避你的单身qoute

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

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

This is a good use for sed :

echo "'abc'" | sed "s/'//g"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM