我正在尝试编写一个将转换输入
的Perl脚本( name
( type ....
)
)
进入输出
( name ( type ... ) )
即。匹配( )
的所有这些行合并为一行,我想更新原始文件。
提前致谢
答案 0 :(得分:1)
use strict;
use warnings;
my $file="t.txt"; #or shift (ARGV); for command line input
my $new_format=undef;
open READ, $file;
local $/=undef; #says to read to end of file
$new_format=<READ>;
$new_format=~ s/\n//g; #replaces all newline characters with nothing, aka removes all \n
close(READ);
open WRITE, ">$file"; #open for writing (overwrites)
print WRITE $new_format;
close WRITE;
这是有效的,假设整个文件是一个大表达式。作为参考,要删除所有空格,请使用$new_format=~ s/\s//g;
代替$new_format=~ s/\n//g;
。可以轻松修改它以考虑多个表达式。所有人都必须将$/
重新定义为用于分隔表达式的任何内容(例如,如果只是一个空行:local $/ = /^\s+$/;
)并将所有内容都放入while循环中。对于每次迭代,将字符串推入数组,在文件完全处理后,以您需要的格式将数组内容写入文件。
答案 1 :(得分:0)
((..))语法是否有保证?如果是这样的话,我建议将整个事物合并为一行,然后基于分割()。
my $line = "";
while(<DATA>)
{
$_ =~ s= +$==g; # remove end spaces.
$line .= $_;
}
$line =~ s=\n==g;
my @lines = split /\)\(/,$line;
my $resulttext = join ")\n(", @lines;
print $resulttext;
__END__
( name
( type ....
)
)
( name2
( type2 ....
)
)
( name3
( type3 ....
)
)
答案 2 :(得分:0)
这是另一种选择:
use strict;
use warnings;
while (<>) {
chomp unless /^\)/;
print;
}
用法:perl script.pl inFile [>outFile]
示例数据:
( name
( type ....
)
)
( name_a
( type_a ....
)
)
( name_b
( type_b ....
)
)
输出:
( name ( type .... ) )
( name_a ( type_a .... ) )
( name_b ( type_b .... ) )
该脚本删除输入记录分隔符,除非读取的行包含最后一个右键paren(与该行上的第一个char匹配)。
希望这有帮助!