How to run a stream based command in place on a file

Vince Hoffman jhary at unsane.co.uk
Mon Oct 18 05:48:28 PDT 2004



On Mon, 18 Oct 2004, Richard Bradley wrote:

> 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?

Not sure about tr but sed does give the -i option to edit in place.

I'm not sure about a more general solution though.

>
> 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?
>
> Thanks in advance,
>
>
> Rich
>
> _______________________________________________
> freebsd-questions at freebsd.org mailing list
> http://lists.freebsd.org/mailman/listinfo/freebsd-questions
> To unsubscribe, send any mail to "freebsd-questions-unsubscribe at freebsd.org"
>


More information about the freebsd-questions mailing list