bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to remove a specific line in a file


From: Matthew Woehlke
Subject: Re: How to remove a specific line in a file
Date: Tue, 01 May 2007 10:41:34 -0500
User-agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.10) Gecko/20070221 Thunderbird/1.5.0.10 Mnenhy/0.7.4.0

Eka1618 wrote:
I am currently trying to figure out how to remove a specific line in a file.
So far I've only been able to come up with Ideas such as removing blank
lines, duplicate lines, or a number of line that are one right after
another. I think that I should be using the commands grep, cat, and rm along
with pipes to somhow make this work.

Nope... you want to be using 'sed' (and this has nothing to do with bash, you should ask on a linux users' list). 'rm' removes files, not lines.

Your first try was actually "close" (you want to be using $(command) not 'command', the latter does not execute programs but prevents expansions from occurring, i.e. treats the contents as a literal string) if you want to remove the first line, but using sed is much easier.

To remove line 5 from 'myfile' and write the result to 'mynewfile':
$ sed '5d' myfile > mynewfile

To remove all lines containing 'FOO' (same files):
$ sed '/FOO/d' myfile > mynewfile

To do both, and also delete lines 5-7:
$ sed -e '5d' -e '/FOO/d' -e '5,7d' myfile > mynewfile

Note that redirecting output to an input file is not recommended (you might end up truncating the file, for example). If you need to replace the file, it is best to write to a temporary file and use e.g. 'mv mynewfile myfile' when you are done.

It seems like there should be a way to delete the first match in pure sed, but I didn't figure it out in the few seconds testing I did. Anyway you can use 'grep -N' to get a line number to feed to sed. Also be sure to read the sed documentation, usually done with 'info sed'.

--
Matthew
"Will somebody get this walking carpet out of my way?!"
  -- Princess Leia Organa





reply via email to

[Prev in Thread] Current Thread [Next in Thread]