How do you delete all lines in a file that begin with "string" in sh? I was thinking about using the sed command.
Asked
Active
Viewed 4.9k times
4 Answers
37
grep -v '^string' yourfile.txt > stripped.txt

Marc B
- 356,200
- 43
- 426
- 500
-
how about out of the same file? – t3hcakeman Nov 09 '11 at 16:37
-
Can't really do that with grep. but you could output to a temp file then `mv tempfile origfile`. If you want true in-place editing, then sed/perl/awk would need to be used. – Marc B Nov 09 '11 at 16:39
-
how would I use those then? :D – t3hcakeman Nov 09 '11 at 16:41
-
1http://ptankov.wordpress.com/2008/04/09/howto-delete-a-line-in-place-with-gnu-sed/ – Marc B Nov 09 '11 at 16:42
-
didn't work, only reprinted the lines EXCEPT the lines containing the string – t3hcakeman Nov 09 '11 at 17:00
-
actually that was my error, it DID how ever make a new file with the filename plus -e at the end of the extension – t3hcakeman Nov 09 '11 at 18:02
-
Use `| sponge $inputfile` from the package `moreutils` to use the same file – trallnag May 17 '20 at 14:02
36
To do it in place, if your sed supports the -i option, you can do:
sed -i '/^string/d' input-file

William Pursell
- 204,365
- 48
- 270
- 300
-
4sed is expecting a file extension for backup when using `-i`, in OS X you must be very pedantic, so explicitly use single quotes: `sed -i '' '/^string/d' input-file` – Joel Bruner Sep 23 '13 at 17:49
-
3In OSX, the default `sed` doesn't even support `-i`! My personal preference is to never use `-i` and do redirections with the shell instead. – William Pursell Sep 23 '13 at 22:01
-
-
It doens't work in ksh? If text has line as 'string-d' then? doesn't work – rohansr002 Jan 30 '20 at 13:03
3
sed and grep in your answers are missing their friend awk:
awk '!/^string/' inputfile > resultfile

Kent
- 189,393
- 32
- 233
- 301
1
You can use Vim in Ex mode:
ex -sc g/^string/d -cx file
g
select all matching linesd
deletex
save and close

Zombo
- 1
- 62
- 391
- 407