How would I use sed to delete all lines in a text file that contain a specific string?
Join Stack Overflow to learn, share knowledge, and build your career.
|
|
|
To remove the line and print the output to standard out:
To directly modify the file:
To directly modify the file (and create a backup):
For Mac OS X users:
|
|||||||||||||||||||||
|
|
there are many other ways to delete lines with specific string besides awk
Ruby (1.9+)
Perl
Shell (bash3.2+)
GNU grep
and of course
|
|||||||||||||||||||||
|
|
You can use sed to replace lines in place in a file. However, it seems to be much slower than using grep for the inverse into a second file and then moving the second file over the original. e.g.
or
The first command takes 3 times longer on my machine anyway. |
|||||||||||||||||||||
|
|
The easy way to do it, with GNU
|
|||||||||||||
|
|
You may consider using
where:
Above example is POSIX-compliant method for in-place editing a file as per this post at Unix.SE and POSIX specifications for The difference with
unless you enjoy unportable code, I/O overhead and some other bad side effects. So basically some parameters (such as in-place/ |
|||||||||||||||||
|
|
I was struggling with this on Mac. Plus, I needed to do it using variable replacement. So I used:
where |
|||||
|
|
To get a inplace like result with
|
|||||
|
|
You can use this also
here -v will print only other than your pattern(that means Invert match) |
|||
|
|
|
I have made a small benchmark with a file which contains approximately 345 000 lines. The way with I have tried both with and without the setting LC_ALL=C, it does not seem change the timings significantly. The search string (CDGA_00004.pdbqt.gz.tar) is somewhere in the middle of the file. Here are the commands and the timings:
|
|||
|
|
|
SED: AWK: GREP: |
||||
|
|
|
|||
|
|
|
|
|||
|
|
|
Just in case someone wants to do it for exact matches of strings, you can use -w flag in grep, w for whole. That is, for example if you want to delete the lines that have number 11 but keep the lines with number 111:
Also works with -f flag if you want to exclude several exact patterns at once. If "blacklist" is a file with several patterns on each line that you want to delete from "file":
|
|||||
|
protected by Community♦ Dec 9 '14 at 14:39
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?