Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Prepending to a file

by sierrathedog04 (Hermit)
on Feb 06, 2001 at 08:07 UTC ( [id://56607]=note: print w/replies, xml ) Need Help??


in reply to Prepending to a file

A now-defunct website that I found on Google offers solutions which you can run from within Perl by using the backtick operator. These solutions depend upon the OS within which Perl runs.
Given a textfile, file1, one may wish to prepend or insert an external file, fileT, to the top of it before processing the file. Normally, this should be done from the Unix or DOS shell before passing file1 on to sed (MS-DOS 5.0 or lower needs 3 commands to do this; for DOS 6.0 or higher, the MOVE command is available):
copy fileT+file1 temp # MS-DOS command 1 echo Y | copy temp file1 # MS-DOS command 2 del temp # MS-DOS command 3 cat fileT file1 >temp; mv temp file1 # Unix commands
UPON FURTHER CONSIDERATION...I was wrong. The UNIX cat solution above is probably simply reading the file into memory as text and writing it out again.

The DOS copy fileT+file1 temp only seems to work with text files, not with binary ones. Therefore it also is probably simply copying a file into memory as text and writing it out again.

Therefore the correct answer is probably the one given earlier in this thread. You cannot do it without complicated manipulation of file pointers. Maybe you cannot do it at all. And there is no ready-made command in Perl or the DOS or UNIX shells to do it.

Replies are listed 'Best First'.
Re: Re: Prepending to a file
by baku (Scribe) on Feb 06, 2001 at 20:47 UTC

    The DOS 'copy' command has a -b option to act upon files in 'binary mode,' analogous to Perl's binmode; and depending upon your 'cat' implementation, the fileT and file1 are most likely read through memory in chunks (4K? I think? --something about that being the optimal size for disc transactions...), so that should be a valid way to do this without bring the whole file into RAM. e.g.

    [dos-prepend.bat] copy /b prepend+original newfile if errorlevel 1 goto abort copy /y newfile original if errorlevel 1 goto abort del newfile del prepend abort: rem end # vs. [unix-prepend] #!/bin/sh cat prepend original > newfile && ( mv -f newfile original; rm -f prepend )

    Of course, dkubb's subroutine is a much better way to cope with this situation.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://56607]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-28 23:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found