Delete a specific line from a text file with sed

by
Ryan
on
October 26, 2008

At some point you may have the need to remove all lines within a text file that match a certain pattern. Accomplishing this is easy with the sed command.

Here is the command format.

$ sed -i '/PATTERN/ d' file.txt
  • The ‘-i‘ option allows you to edit the specified file in place.
  • PATTERN is a regular expression
  • d is a command which instructs sed to delete the line if it matches the PATTERN

Here is an example.

$ cat file.txt
one
two
three
one hundred

We want to remove the lines containing the word “one”

$ sed -i '/one/ d' file.txt
$ cat file.txt
two
three

If your pattern contains an environment variable, you can surround it with double quotes instead to force the shell to expand it.

$ sed -i "/$MYVAR/ d" file.txt
2 Comments
bash
, , , ,

No related posts.

Comments (2)

I need to used sed with already defined variables, e.g.
VAR=one
sed -i ‘/$VAR/ d’ file.txt
The above example will not work since $VAR is not replaced by its content before sed will evaluate the pattern.
Is there a way to do this ?

Thanks for the comment. I have updated the article to answer your question.

Trackbacks (0)

No trackbacks yet

Leave a Comment

(displayed with your post)
(will not be published)
(optional)
Copyright 2008-2010 WiredRevolution.com. All rights reserved.