Delete a specific line from a text file with sed


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.

  • 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.

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

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

  • Bogdan Cristea

    I need to used sed with already defined variables, e.g.
    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 ?

  • Ryan

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

  • Len Richards

    If I use this command to remove the word Art it also removes lines with Artists, etc. I am having no luck in finding how to remove lines with a specific word only. Any help would be appreciated

    Art Covers
    Various Artists

    • Ryan

      The easiest way would be to add a space.
      $ sed -i '/Art\ / d' file.txt

      Good Luck

  • http://none simba

    what happens if you want to add more patters to one sed command for example:

    sed -e ‘s/search term/search term/search term/ d’ output_file

    Lets say I have a file that needs “all” lines deleted that have the following “search terms” nested in them?

  • SilversleevesX

    I’ve noticed with sed, if something doesn’t work with single quotes (aka apostrophes), then try double-quotes. If it still doesn’t work, substitute another symbol for the slashes, ie | or #. If that still doesn’t work, go to the man page or one of these help pages. *G*