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.
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.
-
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.– mvdsCommented Apr 7, 2011 at 16:42
-
4This does not work.This deletes string.I want to delete line that contains this string– virtueCommented Apr 7, 2011 at 16:59
-
7It does work. It answers your question. You could use
grep -v
if you want to simply drop lines containing a certain string.– mvdsCommented Apr 7, 2011 at 17:23 -
1This is working in busibox, while
sed -i '/pattern/d'
does not (removes all the line, not the string)– daniusCommented Jan 28, 2018 at 15:53
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.
-
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.– MikeCommented 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– daniusCommented 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
-
@pedromss: That's for deleting a word, not the line containing the word. Commented Dec 28, 2019 at 3:45