46

I want to delete a line containing a specific string from the file. How can I do this without using awk? I tried to use sed but I could not achieve it.

0

3 Answers 3

73

This should do it:

sed -e s/deletethis//g -i *
sed -e "s/deletethis//g" -i.backup *
sed -e "s/deletethis//g" -i .backup *

it will replace all occurrences of "deletethis" with "" (nothing) in all files (*), editing them in place.

In the second form the pattern can be edited a little safer, and it makes backups of any modified files, by suffixing them with ".backup".

The third form is the way some versions of sed like it. (e.g. Mac OS X)

man sed for more information.

6
  • I think it is usually a better idea to quote the expression and in addition I'd like to point out the -i.bak syntax where sed creates a backup file with the extension given. I.e. could be -i.backup, too ... Commented Apr 7, 2011 at 16:40
  • 1
    @STATUS you're right, some versions of sed actually need the suffix.
    – mvds
    Commented Apr 7, 2011 at 16:42
  • 4
    This does not work.This deletes string.I want to delete line that contains this string
    – virtue
    Commented Apr 7, 2011 at 16:59
  • 7
    It does work. It answers your question. You could use grep -v if you want to simply drop lines containing a certain string.
    – mvds
    Commented Apr 7, 2011 at 17:23
  • 1
    This is working in busibox, while sed -i '/pattern/d' does not (removes all the line, not the string)
    – danius
    Commented Jan 28, 2018 at 15:53
37
sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source doesn't work: sed '/pattern/d' FILE > FILE so make a copy before trying out, if you doubt it. The redirection to a new file FILE will open a new file FILE before reading from it, so reading from it will result in an empty input.

8
  • 2
    This is the correct answer to the original question. For safety reasons, you could use -i.bak instead of just -i to create a backup of your original file.
    – Mike
    Commented Jan 26, 2017 at 14:05
  • This is not working on busybox's sed, it removes all the line not the string, @mvds answer works
    – danius
    Commented Jan 28, 2018 at 15:52
  • @danigosa: Well, that's why mvds answer is wrong, The question was, to remove a line, not the string. Read the question, read the comment of virtue in the most upvoted answer. Commented Jan 29, 2018 at 2:44
  • 1
    Didn't work on macOS. Had to do sed 's/pattern//g'
    – pedromss
    Commented Dec 27, 2019 at 17:04
  • @pedromss: That's for deleting a word, not the line containing the word. Commented Dec 28, 2019 at 3:45
2

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

Not the answer you're looking for? Browse other questions tagged or ask your own question.