Re: I/O redirection problem

From: Stephane CHAZELAS (this.address_at_is.invalid)
Date: 05/26/04


Date: Wed, 26 May 2004 12:54:38 +0000

2004-05-26, 04:32(-07), Krit Kasemosoth:
> I have data file 'test.txt'. I want to search text in that file and
> store
> the result back to file 'test.txt'. The command that I execute is :
>
> cat test.txt | grep monday > test.txt
[...]

That's a common error.

"cat test.txt" and "grep monday > test.txt" are two commands run
at the same time. The right one opens the test.txt file with
truncation, so reduces it to an empty file. If the left one has
not opened test.txt for reading before, it sees an empty file.
Even if it opened it before, you may have unexpected results.

You shouldn't read and write to a same file at the same time.
Use a temporary file or make so that the file written to is a
new instance of the same file:

{ rm test.txt && grep monday > test.txt; } < test.txt

(Here, the former test.txt is opened for reading, then removed,
and a new one is opened for writing).

Alternatively, you can use:

perl -ni -e 'print if /monday/' test.txt
or
ex -s -c 'v/monday/d|wq' test.txt

(none tested).

-- 
Stephane


Relevant Pages

  • Re: A question about fill_free_list(void) function
    ... I'm reading the CPython interpreter source code, ... The code is abusing the ob_type member to store a single linked, ... return (PyObject *) v; ...
    (comp.lang.python)
  • Re: Alternatives to Bifocals
    ... I have reading glasses for at home, ... It is a big pain in the ass to try to use bifocals on a computer all day, so this is a simple solution that may well cost less than Bi or Tri focals or progressive lens. ... I always carry both pair with me when I go to the store, and swap them when I get into the store so I can read labels and such. ...
    (soc.senior.issues)
  • Re: OT Son just finished reading the new Harry Potter book
    ... With the help of a public address system the store organized the crowd ... stayed up all night reading and just ... bed quilt and wall hanging with a Harry Potter theme several books ...
    (rec.crafts.textiles.quilting)
  • Re: A question about fill_free_list(void) function
    ... I'm reading the CPython interpreter source code, ... The code is abusing the ob_type member to store a single linked, ... return (PyObject *) v; ...
    (comp.lang.python)
  • Re: Data logging... how to.
    ... I need to measure a temperature, and store it for later readout. ... I will be using an AVR for temp. ... Now, after the year, the data will be shifted continously, so there will always be the latest data reading about 12 months back. ...
    (sci.electronics.design)