Saturday, July 23, 2011

Adding line no in the files perl

Content of the list.txt:

Hi gopal,how are you
Hi james,how are you
Hi,how are you
Hi Thomas,how are you
Hi Manjula,how are you
Hi karthik,how are you

Content of perl file:

#!/usr/bin/perl
use File::Copy;
open(FH,"<list.txt");

@ddd=<FH> ;
close(FH);
#For creating the temp file and adding the line no
open(FH1,">list.txt.bak");
$size=scalar(@ddd);
for ( $i=0;$i<$size;$i++)
{
$ddd[$i]=~ m/(.*)/;
$dd="$i: "."$1"."\n";
print FH1 $dd;
}
close(FH1);
move("list.txt.bak","list.txt") or die "cannot move";
# for moving the temp file to the original files
unlink("list.txt.bak") or die "cannot delete the file";
# for removing the temp file

Content of the list.txt after execution of the perl file:

0: Hi gopal,how are you
1: Hi james,how are you
2: Hi,how are you
3: Hi Thomas,how are you
4: Hi Manjula,how are you
5: Hi karthik,how are you

Analysis:

Here i have tried add the line no in the file list.txt.For this i have created a tmp file
list.txt.bak and added the line no in those file by using the array index and later replaced the original file list.txt with tmp file:

No comments:

Post a Comment