Reputation: 237
How do I extract abc from 'abc' using a Perl regular expression?
I tried
echo "'abc'" | perl -ne 'if(/\'(.*)\'/) {print $1}'
but it showed:
-bash: syntax error near unexpected token `('
Upvotes: 4
Views: 2354
Reputation: 1904
Precede your single-quoted Perl code with a dollar sign to direct Bash to use an alternate quoting method that turns off shell expansion:
echo "'abc'" | perl -ne $'if(/\'(.*)\'/) {print $1}'
Upvotes: 3
Reputation: 1227
You need to escape your single quote with ''':
echo "'abc'" | perl -ne 'if( /'\''(.*)'\''/ ){print $1}'
Upvotes: 1
Reputation: 241898
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, and start of single quotes):
echo "'abc'" | perl -ne 'if(/'\''(.*)'\''/) {print $1}'
Upvotes: 7
Reputation: 2706
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}'
Upvotes: 2
Reputation: 39158
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}'
Upvotes: 2
Reputation: 62054
You have a shell quoting problem, not a Perl problem.
This is a good use for sed
:
echo "'abc'" | sed "s/'//g"
Upvotes: 2