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.

- 5,753
- 72
- 57
- 129

- 583
- 2
- 8
- 11
3 Answers
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.

- 45,755
- 8
- 102
- 111
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.

- 35,537
- 11
- 75
- 121
-
2This 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 Jan 26 '17 at 14:05
-
This is not working on busybox's `sed`, it removes all the line not the string, @mvds answer works – danius Jan 28 '18 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. – user unknown Jan 29 '18 at 02:44
-
1
-
@pedromss: That's for deleting a word, not the line containing the word. – user unknown Dec 28 '19 at 03:45
-
-
@Freedo: Please note the different topic of headline and question text. – user unknown Mar 28 '20 at 16:26
-
@pedromss, your code is good for test to print to stdout, but not to change the file if your os supports the use of the i flag. – Timo Nov 03 '20 at 17:18
//g" -i *` – james-see Jun 08 '20 at 19:18