Delete lines containing a specific word

Grant Edwards grante at visi.com
Sun Jan 6 19:42:01 EST 2008


On 2008-01-06, Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote:
> On Sun, 06 Jan 2008 13:33:52 -0800, Francesco Pietra wrote:
>
>> Steven:
>> Thanks. See below please (of very marginal interest)
>> 
>> --- Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote:
>> 
>>> On Sun, 06 Jan 2008 09:21:33 -0800, Francesco Pietra wrote:
>>> 
>>> > Please, how to adapt the following script (to delete blank lines) to
>>> > delete lines containing a specific word, or words?
>>> 
>>> That's tricky, because deleting lines from a file isn't a simple
>>> operation. No operating system I know of (Windows, Linux, OS X) has a
>>> "delete line" function.
>> 
>> As I am at Debian Linux, I do that with grep -v
>
> grep doesn't delete lines. grep matches lines.

grep does far more than that.

> If you want to delete them, you still have to do the rest of
> the job yourself.

Nonsense. 

How is this not doing what the OP asks?

   grep -v pattern infile >outfile; mv outfile infile

If you don't like explicitly using a second file, you can use
sed:

  sed -i '/pattern/d' filename

>>> Secondly, you might want the script to write its output to a file,
>>> instead of printing. So, instead of the line "print line", you want it
>>> to write to a file.
>> 
>> may be cumbersome, though I use  2>&1 | tee output file.pdb so that I
>> can see what happens on the screen and have the modified file.
>
> Yes, matching lines and sending them to stdout is a better
> solution than trying to delete them from a file.

If you're matching all lines that don't contain the pattern in
question, then matching all lines and sending them to stdout
_is_ a way to delete them.

-- 
Grant Edwards                   grante             Yow! And furthermore,
                                  at               my bowling average is
                               visi.com            unimpeachable!!!



More information about the Python-list mailing list