add to first line of file using perl

Hey guys,

I have a text file full of data and all I want to do with the thing is add the file extension name to the first line of the file. Here is what I have so far. I can't remember how to append to the first line of the file without deleting the exsisting data.

#!/usr/local/bin/perl

#Dir where all host files are kept.
$dir = '/export/home/joe/scripts/testfiles/';

#Pull all files in dir to array.
opendir(DIR, "$dir") || die("Cannot open directory");
@dir = readdir(DIR);
closedir(DIR);

for $file(<@dir>) {
if ($file =~ /insertline\.(.*$)/) {

  $addtofile = uc\("!$1\\n"\);
  $modfile = "$dir$file";

  open\(FILE, $modfile\) || die\("Cannot open file"\);
  \#insert $addtofile var here but do it at line 1
  \#UGH!!  :confused: 

}
}
close FILE;
exit (0);

Does it have to be perl?

#!/bin/ksh
a=file.txt
echo "${a#file.}" > tmp.tmp
cat "$a" >> tmp.tmp
mv tmp.tmp $file

Yea,

I'd like to add it to my existing script I have that generates my host files for me.

If you're not too concerned about the kludge, you could just embed that shell stuff into the perl script, and get the same effect.

I suppose, but is it really that hard to do it in perl? I though I have done it before with a seek command or something but im drawing a blank.

EXAMPLE: In case anyone needs to do something similar here is what I made. I will go back and change some var names so its more readable but you get the idea. I'd still like to know how to write to the first line of the file without having to make a duplicate using perl. If any one knows that be cool please post.

$ cat insertline.pl
#!/usr/local/bin/perl

#Dir where all host files are kept.
$dir1 = '/export/home/joe/scripts/testfiles/';
$dir2 = '/export/home/joe/scripts/testfiles/finalchanges/';

#Pull all files in dir to array.
opendir(DIR1, "$dir1") || die("Cannot open directory");
@dir1 = readdir(DIR1);
closedir(DIR1);

for $file(<@dir1>) {
if ($file =~ /insertline\.(.*$)/) {
$addtofile = uc("!$1\n");
$modfile1 = "$dir1$file";
$modfile2 = "$dir2$file";

  open\(FILE1, "$modfile1"\) || die\("Cannot open file"\);
  open\(FILE2, "&gt;$modfile2"\) || die\("Cannot open file"\); 
  print FILE2 "$addtofile";
  @copy_this = &lt;FILE1&gt;;
  print FILE2 \(@copy_this\);
  close \(FILE1\);
  close \(FILE2\);

}
}
exit (0);

I guess I could dump thee current text file to an array like this and just write over the existing file instead of making a second file. I thought there was a cleaner way of doing it but whatever haha :smiley: