[lug] Changing files on-the-fly

John Hernandez John.Hernandez at noaa.gov
Tue Sep 16 09:25:03 MDT 2003


Perl has a nice one-liner approach to this, using the -i switch. For 
example (from the perlrun manpage):

perl -pi -e ’s/bar/baz/’ fileA

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. :)
>
>TIA,
>Jeff
>
>_______________________________________________
>Web Page:  http://lug.boulder.co.us
>Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
>Join us on IRC: lug.boulder.co.us port=6667 channel=#colug
>
>  
>




More information about the LUG mailing list