Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I am new to Perl programming and I am stuck with this problem for some time. Can you please help me in solving it?

I have a file with the following format:

>Country1 
Aus
trali
a

>Country5
Swi
tzer
land

>Country2
Net
herland
s

I want to output a file with the following format:

>Country1 Australia
>Country5 Switzerland
>Country2 Netherlands
share|improve this question
1  
What determines the places where you want a line break: where the input contains an empty line, or before >? –  Gilles Jul 20 at 22:25

2 Answers 2

A straight Perl solution:

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

or a shorter way:

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

Set $/ to empty string causes Perl switch into paragraph mode, meaning record separator is one or more blank lines.

share|improve this answer

Use the -p switch to process the file line by line and output each processed line. Replace the newline by a space if the line starts with >, and by nothing if it starts by another non-newline character (i.e. if it isn't empty).

perl -pe 'if (/^>/) {s/\n/ /} elsif (/^./) {s/\n//}'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.