LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (http://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   adding new line after each line in perl (http://www.linuxquestions.org/questions/linux-newbie-8/adding-new-line-after-each-line-in-perl-877214/)

KManepalli 04-26-2011 01:14 PM

adding new line after each line in perl
 
Hi

I need to add extra line after end of each line in perl.
I have file with data like below.
12345
67890
abcde

I need the data to be:
12345

67890

abcde

I am using the below code to achieve this.Here i am opening the file, looping through all the records and adding "\n" at the end of each record. But I am not getting what i wanted. Any suggestions??

***********************
my $thisFILE="$Filepath";

open (my $FILE,"<", $thisFILE) or die "Argh!";
while (my $rec=<$FILE>){
print "Entered into while loop\n";
$rec=$rec."\n";
}
**********************

Thanks
K.

adam999 04-26-2011 02:13 PM

my $thisFILE="$Filepath";

open (my $FILE,"<", $thisFILE) or die "Argh!";
my $newrec;
while (my $rec=<$FILE>){
print "Entered into while loop\n";
$newrec .= $rec."\n";
}

print $newrec;

KManepalli 04-27-2011 10:55 AM

Thanks adam999. This just worked fine.
Thanks for your help !!

K

grail 04-27-2011 11:38 AM

This seems like a lot of hard work for something trivial ... are you just looking to improve your Perl skills? Or maybe this is a small part of something bigger?

theNbomr 04-27-2011 03:21 PM

Quote:

Originally Posted by grail (Post 4338231)
This seems like a lot of hard work for something trivial

That's what I first thought, too. However my initial reaction to use either sed or tr both failed me. My best was this:
Code:

perl -i -e 'while(<>){print $_."\n";}' /home/my/file.ext
What is the real solution?
--- rod.

w1k0 04-27-2011 07:22 PM

Assuming you have file.ext including a few text lines to insert empty line after each line is enough to run the following command:

sed -i 's/$/\n/' file.ext

grail 04-27-2011 08:34 PM

Or
Code:

awk 'ORS=RT"\n"' file

colucix 04-27-2011 08:46 PM

Or even
Code:

sed G file

grail 04-27-2011 10:01 PM

Now that is sweet :)

theNbomr 04-28-2011 08:02 AM

I knew you guys were good...
--- rod.


All times are GMT -5. The time now is 03:11 PM.