Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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:




I want to output a file with the following format:

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

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


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.