#!/usr/bin/perl -w use strict; use warnings; my $found_f = 0; my ( $lastline, $line ); open( INPUTFILE, "test.txt" ); while () { chomp; if (/^[A-Z]{2}:\s/) { $lastline = $line; $line = $_; $found_f = 1; } elsif ( !/^[A-Z]{2}:\s/ && $found_f ) { s/^ {4}/ /; $line .= $_; next; } elsif (/^$/) { $lastline = ' '; $found_f = 0; } print "$lastline\n"; }