我有多个文件,其中包含某些代码块、多行,我需要将其注释掉。我对一些包含特定关键字的特殊 block 感兴趣:
ic create
这些 block 总是以
开头%put %str
结束于
%rcSet
示例 block 如下:
text
text
text
%put %str(NOTE: integrity constraints);
proc datasets library=TESTING nolist;
modify TESTING_UPDATES;
ic create not null (id);
ic create not null (prsn);
ic create not null (valid_from);
ic create not null (valid_to);
ic create not null (current_flag);
ic create not null (active_flag);
ic create not null (hist);
quit;
%rcSet(&syserr);
%put %str(NOTE: integrity constraints);
proc datasets library=TESTING nolist;
modify TESTING_UPDATES;
quit;
%rcSet(&syserr);
可能有更多以指定关键字开头和结尾但没有“ic create”关键字的 block ,需要忽略。
我已经编写了一个代码来查找并显示所有这些 block ,但我无法计算
- 我怎样才能从头到尾得到这些在中间具有所需模式的 block
- 什么是最好的评论方式,在行首添加*,从头到尾都是
- 代码最好没有任何外部模块,因为将来阅读本文的每个人都可能无法访问它们
期望的输出:
text
text
text
* %put %str(NOTE: integrity constraints);
* proc datasets library=TESTING nolist;
* modify TESTING_UPDATES;
* ic create not null (id);
* ic create not null (prsn);
* ic create not null (valid_from);
* ic create not null (valid_to);
* ic create not null (current_flag);
* ic create not null (active_flag);
* ic create not null (hist);
* quit;
*
* %rcSet(&syserr);
%put %str(NOTE: integrity constraints);
proc datasets library=TESTING nolist;
modify TESTING_UPDATES;
quit;
%rcSet(&syserr);
我的 Perl 代码:
use strict;
use warnings;
my @files = glob ("*.sas");
foreach my $file (@files) {
open my $fh, '<', $file or die "Cannot open file: $!"; {
while ( <$fh> ) {
if ( /%put\s%str/ ) {
print;
while ( <$fh> ) {
print;
last if /%rcSet/;
}
print "-" x 20, "\n";
}
}
__END__
非常感谢任何帮助。谢谢!
最佳答案
您正在逐行工作,并试图“知道”节中是否有“ic create”。
因此,解决它的方法是:
#!/usr/bin/env perl
use strict;
use warnings;
my $buffer;
while (<>) {
if ( m/\%put\s\%str/ .. /\%rcSet/ ) {
$buffer .= $_;
next;
}
if ($buffer) {
if ( $buffer =~ m/ic create/ ) {
$buffer =~ s/^/*/gm;
}
print $buffer;
$buffer = "";
}
print;
}
#handle the case of buffer being the last line:
if ($buffer) {
if ( $buffer =~ m/ic create/ ) {
$buffer =~ s/^/*/gm;
}
print $buffer;
}
关于linux - 在多个文件中注释特定代码块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43851419/