Date: Wed, 26 Feb 2003 17:14:56 +0000 From: Matthew Seaman <m.seaman@infracaninophile.co.uk> To: freebsd-questions@FreeBSD.ORG Subject: Re: cat Message-ID: <20030226171456.GA77795@happy-idiot-talk.infracaninophi> In-Reply-To: <20030226175613.5e61f45e.tijl@ulyssis.org> References: <20030226175613.5e61f45e.tijl@ulyssis.org>
next in thread | previous in thread | raw e-mail | index | archive | help
On Wed, Feb 26, 2003 at 05:56:13PM +0100, Tijl Coosemans wrote:
> I want to remove CRs from text files so what I did is this:
>
> cat filename | tr -d '\r' > filename
>
> However, I often end up with an empty file. Just out of
> interest, somebody who knows why that is?
Hmmm... That's a nasty race condition. In my experience of
accidentally doing something like that, it has *always* ended up with
an empty file. The problem is that you are attempting both to read
from and write to the same file simultaneously. Any shell pipeline of
the form:
command > filename
implies that the shell is going to open 'filename' O_TRUNC (see
open(2)) -- hence shortening the file to zero length, before forking
and exec'ing the command with its stdout redirected to that filename.
Much the same sort of thing can happen when you supply the filename on
the command line rather than using the shell redirection operators to
supply the data on stdin or stdout. There are commands that can do
in-place edits, eg 'perl -i', 'sed -i' (in recent versions of
FreeBSD), but these do some sleight of hand behind the scenes to
arrange that opening the file for output does not trash it for input,
and they certainly won't do in-place edits when used with the shell's
redirection operators.
The general solution to your problem is always to write to a different
file than what you read:
tr -d '\r' < filename > filename.n && mv filename.n filename
(Note too the influence of the Society for the Suppression of Stray
Cats -- save a process today!)
Cheers,
Matthew
--
Dr Matthew J Seaman MA, D.Phil. 26 The Paddocks
Savill Way
PGP: http://www.infracaninophile.co.uk/pgpkey Marlow
Tel: +44 1628 476614 Bucks., SL7 1TH UK
To Unsubscribe: send mail to majordomo@FreeBSD.org
with "unsubscribe freebsd-questions" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20030226171456.GA77795>
