From owner-freebsd-questions@FreeBSD.ORG Tue Oct 19 15:30:03 2004 Return-Path: Delivered-To: freebsd-questions@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id DED0916A4CE for ; Tue, 19 Oct 2004 15:30:03 +0000 (GMT) Received: from mail5.speakeasy.net (mail5.speakeasy.net [216.254.0.205]) by mx1.FreeBSD.org (Postfix) with ESMTP id 6221143D39 for ; Tue, 19 Oct 2004 15:30:03 +0000 (GMT) (envelope-from freebsd-questions-local@be-well.ilk.org) Received: (qmail 19510 invoked from network); 19 Oct 2004 15:30:03 -0000 Received: from dsl092-078-145.bos1.dsl.speakeasy.net (HELO be-well.no-ip.com) ([66.92.78.145]) (envelope-sender ) by mail5.speakeasy.net (qmail-ldap-1.03) with SMTP for ; 19 Oct 2004 15:30:02 -0000 Received: by be-well.no-ip.com (Postfix, from userid 1147) id 2ABCDE; Tue, 19 Oct 2004 11:30:02 -0400 (EDT) Sender: lowell@be-well.ilk.org To: Richard Bradley References: <200410181334.37665.rtb27@cam.ac.uk> From: Lowell Gilbert Date: 19 Oct 2004 11:30:01 -0400 In-Reply-To: <200410181334.37665.rtb27@cam.ac.uk> Message-ID: <44r7nuwwsm.fsf@be-well.ilk.org> Lines: 36 User-Agent: Gnus/5.09 (Gnus v5.9.0) Emacs/21.3 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii cc: freebsd-questions@freebsd.org Subject: Re: How to run a stream based command in place on a file X-BeenThere: freebsd-questions@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: User questions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Tue, 19 Oct 2004 15:30:04 -0000 Richard Bradley 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.