Skip site navigation (1)Skip section navigation (2)
Date:      19 Oct 2004 11:30:01 -0400
From:      Lowell Gilbert <freebsd-questions-local@be-well.ilk.org>
To:        Richard Bradley <rtb27@cam.ac.uk>
Cc:        freebsd-questions@freebsd.org
Subject:   Re: How to run a stream based command in place on a file
Message-ID:  <44r7nuwwsm.fsf@be-well.ilk.org>
In-Reply-To: <200410181334.37665.rtb27@cam.ac.uk>
References:  <200410181334.37665.rtb27@cam.ac.uk>

next in thread | previous in thread | raw e-mail | index | archive | help
Richard Bradley <rtb27@cam.ac.uk> writes:

> Hi,
> 
> I want to run stream based commands like `sed` and `tr` on the contents of a 
> file, and save the results to the same file.
> 
> Obviously I can do this with a temporary file:
> 
> $sed s/dog/cat/ myanimals.txt > tmp.txt
> $mv tmp.txt myanimals.txt
> 
> But is there any way I can do this with a single command?
> 
> My first guess would be a "buffer" command that reads a file into memory (or 
> into a temp file) then pipes it to stdout, e.g.
> 
> $cat myanimals.txt | buffer | sed s/dog/cat/ > myanimals.txt
> 
> But there isn't one which, in my experience of BSD, means it either wouldn't 
> work or there is a better way to do it :-)
> 
> Having read through the Bash manual and run some experiments, it seems that 
> the ">" operator truncates an output file to zero length before any commands 
> are run.
> 
> So my missing command becomes:
> 
> $cat myanimals.txt | sed s/dog/cat | bufferedwrite myanimals.txt
> 
> I can't find anything like this anywhere -- any ideas what the "proper" way to 
> do this is?

In this specific case, sed(1) has a '-i' option on recent FreeBSD
systems, specifically to handle this case.  For other commands, you
typically write to a different file, and copy it back.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?44r7nuwwsm.fsf>