SPUG: how to add text at start of a already existing file

Brian Hatch bri at ifokr.org
Tue Jan 18 06:59:07 PST 2005



> > hi i want to add text at very start of already existing file.
> > i have tried this code but it is adding only at end
...
> 
> You use open(FH,"+< $file") to open an existing file for reading
> and writing.  Then you need to read in the entire current content
> of the file, because when you write your $msg out, it will overwrite
> what's there already.  After printing $msg, then print the original
> file data.  So:
> 
> open(FH,"+< $file") or die "could not open: $!\n";
> seek FH, 0, 0;
> my $content = do { local $/; <FH> }; # read in whole file
> seek FH, 0, 0;
> print FH $msg, $content;
> close FH or die "could not close: $!\n";

How 'bout

	$ cat unshift_head
	#!/usr/bin/perl -p -i
	BEGIN { $msg = "Stuff I want to add.\n"}

	print $msg if $. == 1;

And then to run it

	$ unshift_head filename

Perl writes the rest because of the '-p' and '-i' switches.


-- 
Brian Hatch                  Those who live by
   Systems and                the sword, die by
   Security Engineer          the arrow.
http://www.ifokr.org/bri/

Every message PGP signed
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://mail.pm.org/pipermail/spug-list/attachments/20050118/5498234a/attachment.bin


More information about the spug-list mailing list