[lug] Changing files on-the-fly

Zan Lynx zlynx at acm.org
Tue Sep 16 09:51:15 MDT 2003

On Tue, 2003-09-16 at 08:31, Jeff Schroeder wrote:
> I've been writing shell scripts for years, and as I write more complex 
> ones I'm repeatedly annoyed by the fact that if I want to change a text 
> file on-the-fly I have to redirect it to a temp file.  For example, 
> let's say I have a four-line text file called numbers.txt:
> one
> two
> three
> four
> I want to remove the line containing 'three' from the file, so I'm left 
> with
> one
> two
> four
> In order to do this (AFAIK) I have to do this:
> grep -v three numbers.txt > .tempfile && mv .tempfile numbers.txt
> Because if I try to do it all at once, via
> grep -v three numbers.txt > numbers.txt
> The resulting file is empty.  Is there a way to NOT use a temporary file 
> for this sort of operation?  I'm not just talking about grep here; I'm 
> including sed or any other tool that would alter a file's contents.  
> Maybe this is just The Unix Way, but I figured I'd ask anyway. :)

As someone else said, perl has the -i switch which will do the temporary
file in the background where you cannot see it.

Editing the file in-place can be done, of course.  The method I saw used
mmap and truncate and memmove.  That is probably more effort than you'd
Zan Lynx <zlynx at acm.org>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 189 bytes
Desc: This is a digitally signed message part
URL: <http://lists.lug.boulder.co.us/pipermail/lug/attachments/20030916/7eca339d/attachment.pgp>

More information about the LUG mailing list