-1

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

例子是

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

在 heros.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.

我哪里错了??

4

1 回答 1

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
  • 最好使用ifor &&(就像在我的 2 个片段中一样)语句来不打印不匹配的行
  • \s已经是一个空格(或空白字符),所以不要重复文字空格和\s

action if condition;

是的简写

if (condition) {action};
于 2013-03-27T15:15:47.410 回答