Perl正则表达式示例不起作用

时间:2013-03-27 15:11:08

标签: perl

我只是想测试一下我在杂志上看过的东西(Linux Shell手册)。我从来没有尝试过这样的事情,但我知道这可能很有用

示例是

perl -n -e '/^The \s+(.*)$/ print "$1\n"' heroes.txt

在heroes.txt中它有

Catwoman
Batman
The Tick
Spider-Man
Black Cat
Batgirl
Danger Girl
Wonder Woman
Luke Cage
Ant-Man
Spider-Woman

这应该显示Tick,但是我得到了

perl -n -e '/^The \s+(.*)$/ print "$1\n"' heroes.txt
syntax error at -e line 1, near "/^The \s+(.*)$/ print"
Execution of -e aborted due to compilation errors.

我哪里错了?

1 个答案:

答案 0 :(得分:5)

最好这样做:

$ perl -lne 'print $1 if /^The\s+(.*)$/' heroes.txt
Tick

$ perl -lne '/^The\s+(.*)$/ && print $1' heroes.txt
Tick

您的原始命令有一些错误:

perl -n -e '/^The \s+(.*)$/ print "$1\n"' heroes.txt
  • 这是语法错误,您无法使用m//匹配运算符,m如果与/分隔符一起使用,则不是必需的) print
  • 更好地使用if&&(如我的2个代码段中)声明不打印不匹配的行
  • \s已经是空格(或空白字符),因此请勿重复文字空间和\s

action if condition;

的简写
if (condition) {action};