open(IN,"in.txt"); while() { if($_=~m/^\n/) { $tell_val=tell(); } if($_=~m/^\d+/) { $has{$&}=$tell_val if($tell_val ne ''); } } open(OUT,">output.txt"); foreach(sort{$a<=>$b}(keys %has)) { seek(IN,$has{$_},0); $line=; print OUT $line; print $_; }