Regex Perl从匹配的字符串中删除换行符
我正在尝试解析一些源文件,但遇到了这个问题。我正在搜索匹配其中包含“”的特定字符串,并尝试删除所有换行符,从它找到上述符号开始,直到它遇到第一个“;”符号为止。任何帮助都将不胜感激 这就是我想做的: 输入:Regex Perl从匹配的字符串中删除换行符,regex,perl,Regex,Perl,我正在尝试解析一些源文件,但遇到了这个问题。我正在搜索匹配其中包含“”的特定字符串,并尝试删除所有换行符,从它找到上述符号开始,直到它遇到第一个“;”符号为止。任何帮助都将不胜感激 这就是我想做的: 输入: ... lines of code func1 <<< abc, xyz >>> ( str1, str2, str3); ... lines of co
... lines of code
func1 <<< abc, xyz >>> ( str1,
str2,
str3);
... lines of code
。。。代码行
func1>(str1,
str2,
str3);
... 代码行
输出:
... lines of code
func1 <<< abc, xyz >>> (str1, str2, str3);
... lines of code
。。。代码行
func1>(str1、str2、str3);
... 代码行
变量func1、abc、xyz、str1、str2、str3都可以变化
提前谢谢
编辑:
这是我尝试过的,到目前为止,它只打印与输入相同的模式
while (<$fh>) {
if (/\<\<\<.*\>\>\>/) {
while ($_ !~ /\)\s*\;/) {
chomp $_;
$_ = <$fh>;
}
print $_;
}
}
while(){
如果(/\/){
而($\!~/\)\s*\;/){
大口大口;
$_ = ;
}
打印美元;
}
}
编辑2:
问题已经解决了。参见答案。my@long$end;
my @long, $end;
while (<>) { # read a line
if (/<<<.*>>>/ .. ($end = /;/)) { # if needs joining,
s/^\s+|\s+$//g; # trim it
push @long, $_; # add to list
print join(' ', @long) . "\n" if $end; # paste and print if at end
} else { # if doesn't need joining,
print; # just print without changes
}
}
读一行
如果(/…($end=/;/){#如果需要加入,
s/^\s+|\s+$//g;#修剪它
按@long,$#添加到列表
打印联接(“”,@long)。“\n”如果$end;#如果在末尾粘贴并打印
}否则{#如果不需要加入,
打印;#只需打印而不做任何更改
}
}
好吧,我知道我做错了什么。我试着在原地做。我想这也不是很有效,但它确实有效
编辑:决定不更改原始文件。使用@TLP的有用输入更改了代码
open my $fh, "<", $ARGV[0] or die "$!";
open my $out, ">", "output.out" or die "$!";
while (<$fh>)
{
if (/\<\<\<.*\>\>\>/)
{
while (1)
{
if (/\)\s*\;/) { s/\s//g; last; }
else { s/\s//g;
$_ .= <$fh>; }
}
}
print $out $_."\n";
}
close $out;
close $fh;
打开我的$fh,“,”输出.out“或死亡“$!”;
而()
{
如果(/\/)
{
而(1)
{
如果(/\)\s*\;/){s/\s//g;last;}
else{s/\s//g;
$_ .= ; }
}
}
打印$out$。“\n”;
}
收尾美元;
收盘价$fh;
这应该可以:
perl -npe 'if (/<<<.*?>>>/../;/) { chomp unless /;/ }' filename
perl-npe'if(//../;/){chomp除非/;/}文件名
它的作用如下:
和之间的所有行
并从中删除换行符。对于包含的行不执行此操作代码>
假设我们讨论的是压缩一个包含
的语句,如果一行包含
,那么chomp
它,并连接下一行。冲洗,重复,直到找到代码>位于行的末尾。完成。@TLP:我也尝试了连接。但它仍然不起作用。您没有在该代码中连接。@TLP:我已经尝试了类似$$$$的操作,但它不起作用。“不起作用”不是一个问题描述。您可能对使用-I
开关感兴趣,该开关将为您进行就地编辑。虽然我个人的偏好是不更改任何原件,而是做perl foo.pl input.txt>output.txt
。另外,1)\s
包括\n
,因此不需要两个替换。2) 如果将其中一条print
语句移出if
块,或者使用continue
块,则可以跳过该语句。使用=
通常比使用两个运算符更可取。您不需要转义正则表达式中的所有字符。只有)
需要在那里转义,而您实际上不需要使用它,因为/\s*$/
@TLP:感谢您的输入。谢谢。
#!/usr/bin/perl
use strict;
use warnings;
while ( <DATA> ) {
if ( m/<<</ .. m/\);$/ ) {
s/\s+/ /g;
s/;\s*$/;\n/g;
}
print;
}
__DATA__
... lines of code
func1 <<< abc, xyz >>> ( str1,
str2,
str3);
... lines of code
... lines of code
func1 <<< abc, xyz >>> ( str1, str2, str3);
... lines of code