Fra*_*sca 2 perl text-processing
我有一个具有以下格式的文件:
>Country1
Aus
trali
a
>Country5
Swi
tzer
land
>Country2
Net
herland
s
Run Code Online (Sandbox Code Playgroud)
我想输出以下格式的文件:
>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands
Run Code Online (Sandbox Code Playgroud)
一个直接的Perl
解决方案:
$ perl -lne '
if(/^>/) {printf "%s ", $_;next}
if(/^$/) {printf "\n";next}
printf "%s", $_;
' file
>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands
Run Code Online (Sandbox Code Playgroud)
或更短的方式:
$ perl -ane 'BEGIN{$/="";};print "$F[0] ",@F[1..$#F],"\n"' file
>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands
Run Code Online (Sandbox Code Playgroud)
设置$/
为空字符串会导致 Perl 切换到段落模式,这意味着记录分隔符是一个或多个空行。