Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

i have around 700 files and in each file i have to add one line at start of file.i tried writing a script and used seek fucntion to reach to begninning. but some how i m over writing the existing first line. how this can be done effectively
for example
#include "something.cfg"
#inchule " something2.cfg"
i want to add #something3.cfg at top of file but even i m using seek to reach to top of file i m overwriting first line.

Replies are listed 'Best First'.
Re: add a line in file at start of file
by Zaxo (Archbishop) on Jul 15, 2006 at 01:54 UTC

    Tie::File is handy for that kind of thing.

    use Tie::File; for (glob '*.{c,h}') { tie my @file, 'Tie::File', $_ or warn $! and next; unshift @file, '#include something3.cfg'; }

    The problen with seek and friends is that you wind up overwriting the original first line, as you say.

    Without Tie::File, the way to do this is to write the new first line to a temp file, then copy the rest of the original to temp and rename temp to original.

    After Compline,
    Zaxo

Re: add a line in file at start of file
by rodion (Chaplain) on Jul 15, 2006 at 03:11 UTC
    The task of generating a temporary file and renaming it is greatly simplified by Perl's "-i" option, along with the "-p" option. The "-i" option edits a file in place, and makes a backup with an extension that you specify, such as ".bak". The "-p" option puts a read and print loop around your code. These can be combined with unix "find" command and the "xargs" command to make a nice one-liner for the command line in unix that does it all. Here is one to add a line to all files with the file extentsion ".fileext".
    find . -name '*.fileext' -print0 | xargs -0 perl -pi'.bak' -e 'print " +#something3.cfg\n" unless $c++;'

    If you're on windows, you can build a .bat to do the xargs work. Use an editor to make a file that contains

    perl inplace.pl firstFile.fileext perl inplace.pl secondFile.fileext ...
    Where the inplace.pl file contains
    #!perl -pi'*' print "#something3.cfg\n" unless $cnt++;