Perlでファイルの内容をフォーマットする

Perlでファイルの内容をフォーマットする

次の形式のファイルがあります。

>Country1 
Aus
trali
a

>Country5
Swi
tzer
land

>Country2
Net
herland
s

次の形式でファイルを出力したいと思います。

>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands

ベストアンサー1

直接Perlソリューション:

$ perl -lne '
    if(/^>/) {printf "%s ", $_;next}
    if(/^$/) {printf "\n";next}
    printf "%s", $_;
' file
>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands

またはより短い方法:

$ perl -ane 'BEGIN{$/="";};print "$F[0] ",@F[1..$#F],"\n"' file
>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands

空の文字列に設定すると、$/Perlは短絡モードになります。これは、レコード区切り文字が 1 つ以上の空の縮小であることを意味します。

おすすめ記事