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

Tim Maher tim at consultix-inc.com
Tue Jan 18 10:21:03 PST 2005

On Tue, Jan 18, 2005 at 06:59:07AM -0800, Brian Hatch wrote:
> > > 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
> 	$ 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

I endorse Brian's solution as the most simple and practical,
but I think a better name for it would be "prepend2file".
And I'd also add the following statement to the BEGIN block, in
order to get a different file extension on the backup file on each
run -- that prevents you from trashing the original backup if you
run the script twice:

$^I=".$$";	# Use PID for uniqueness

What the hell, why not add the -s to the shebang line too, and also
-w for extra brownie points, and then supply the message string on the
command line:

 	$ prepend2file -msg='whatever' filename

For those who like this style of programming, I can recommend a
nice upcoming book with tons of examples of this sort 8-}

| Tim Maher, PhD     (206) 781-UNIX      (866) DOC-PERL     (866) DOC-UNIX |
| tim(AT)Consultix-Inc.Com  http://TeachMePerl.Com  http://TeachMeUnix.Com |
|      Watch for my upcoming book: "Minimal Perl for UNIX/Linux People"    |
| Classes:  2/14: Minimal Perl  2/15: Hashes & Arrays  2/16-18: Int. Perl  |

More information about the spug-list mailing list