2013-03-27 49 views
-1

我只是想测试一些我在杂志(Linux Shell Handbook)中看到的东西。我从来没有真正尝试过这样的事,但我知道这可能是有用的Perl正则表达式示例不起作用

的例子是

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 

,这应该显示刻度,但是我越来越

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. 

我在哪里出错?

+0

速记打印 – imran 2013-03-27 15:14:53

+0

之前需要分号不,[我的回答像]需要一个if语句(http://stackoverflow.com/a/15662424/465183) – 2013-03-27 15:21:10

+0

谢谢你的作品,但我怎么能只显示一行 – geekcomputers 2013-03-27 15:25:34

回答

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 
  • 这是一个语法错误,你可以” t使用m//匹配
  • 更好地使用if&&(像我的2段)语句不打印不匹配的行
  • \s已经是一个空间(:运营商,如果与/分隔符使用),其次是printm不是强制性的或者空白字符),所以不重复这两个文字空间和\s

action if condition; 

if (condition) {action}; 
+0

非常感谢 – geekcomputers 2013-03-27 15:26:04

+0

我可以做的厚脸皮,并要求你看看这个例子以及perl -n -e'/ ^(\ w +) - (\ w + )$/print“$ 1 $ 2 \ n”'heroes.txt – geekcomputers 2013-03-27 15:29:52

+1

你甚至读过我的回答吗?为什么再次做同样的错误? – 2013-03-27 15:33:03