如何使用perl正则表达式从'abc'中提取abc?
我试过
echo "'abc'" | perl -ne 'if(/\'(.*)\'/) {print $1}'
但它显示 -bash:意外令牌附近的语法错误`('
提前感谢您的回复。
答案 0 :(得分:7)
这不是一个perl问题,这是一个shell问题:你不能将单引号包含在单引号中。
您必须使用'\''
替换每个单引号(单引号末尾,单引号转义,引号引号)
echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}'
答案 1 :(得分:3)
在带有美元符号的单引号Perl代码之前,指示bash使用alternate quoting method来关闭shell扩展:
echo "'abc'" | perl -ne $'if(/\'(.*)\'/) {print $1}'
答案 2 :(得分:2)
好吧,便宜的方法不是用单引号括起你的perl语句:
echo "'abc'" | perl -ne "if(/'(.*)'/) {print $1}"
Shell逃避有奇怪的规则......
如果你真的想以“正确”的方式做到这一点,你可以结束你的第一个单引号字符串,把引号放入,然后开始另一个:
echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}'
答案 3 :(得分:2)
choroba's answer解决了确切的问题。有关任何引用问题的通用解决方案,请使用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}'
答案 4 :(得分:1)
你需要用'\''
来逃避你的单引号 echo "'abc'" | perl -ne 'if( /'\''(.*)'\''/ ){print $1}'
答案 5 :(得分:1)
你有shell引用问题,而不是Perl问题。
这适用于sed
:
echo "'abc'" | sed "s/'//g"