使用 Perl 从 Java 源文件集合中删除第一个注释
我正在尝试从 Java 源文件集合中删除第一个 C 样式注释(仅第一个)。起初我尝试了多行 sed,但它不能正常工作,所以经过一番谷歌搜索后,似乎 Perl 是最好的选择。我曾经喜欢 Perl,它是我用来制作 Web 程序的第一种语言,但我在尝试让这个脚本工作时遇到了困难:
#!/usr/bin/perl -i.bak
$s=join("",<>);
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/$1 /;
print $s;
我用文件的文件名来调用它进行处理,例如./com.pl test.java。根据互联网上的所有内容,-i(就地编辑)应该将输出从打印语句重定向到文件,而不是打印到标准输出。现在事情是这样的:事实并非如此。无论我如何尝试,我似乎都无法让它用打印输出替换文件。我也尝试过 $^I 但也不起作用。
我不知道这是否相关,但我使用的是 Ubuntu 11.04。
PS 我知道正则化源代码的陷阱:)
I'm trying to remove the first C-style comment (only the first) from a collection of Java source files. At first I tried a multi-line sed, but that didn't work properly so after some Googling it seemed Perl was the way to go. I used to like Perl, it was the first language I ever used to make a web program with, but I've run into a wall trying to get this script to work:
#!/usr/bin/perl -i.bak
$s=join("",<>);
$s=~ s/("(\\\\|\\"|[^"])*")|(\/\*([^*]|\*(?=[^\/]))*\*\/)|(\/\/.*)/$1 /;
print $s;
I call it with the filename(s) of the files to be processed, e.g. ./com.pl test.java. According to everything on the Internet, -i (in-place edit) should redirect output from print statements to the file instead of printing to stdout. Now here's the thing: it doesn't. No matter what I try, I can't seem to get it to replace the file with the print output. I've tried $^I too but that doesn't work either.
I don't know if it's relevant but I'm on Ubuntu 11.04.
P.S. I'm aware of the pitfalls of regexing source code :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下命令在命令行中不起作用吗?
脚本内部
与上述等效的脚本是:
原始帖子缺少
p
标志,如 triplee。有关更多信息,请参阅
perldoc perlrun
。Does the following not work from the command line?
Inside a script
The script equivalent of the above is:
The original post was missing the
p
flag, as pointed out by triplee in his comment.See
perldoc perlrun
for more.