How can I delete all lines that do not begin with certain characters?
17,474
Solution 1
In VIM:
:g!/^[+-]/d
Here is the English translation:
g
lobally do something to all lines that do NOT!
match the regular expression: start of line^
followed by either +
or -
, and that something to do is to d
elete those lines.
Solution 2
sed -e '/^[^+-]/d'
Author by
mager
Updated on June 19, 2022Comments
-
mager almost 2 years
I need to figure out a regular expression to delete all lines that do not begin with either "+" or "-".
I want to print a paper copy of a large diff file, but it shows 5 or so lines before and after the actual diff.
-
SourceSeeker over 14 yearsYou definitely need another caret and may not need "e" or quotes. This works for me:
grep ^[^+-]
-
Joy Dutta over 14 yearsAgree for this particular case. I typically use cat when using a long chain of sed commands to incrementally filter out data. If I have too big a data file to begin with, I replace cat with head -100 and the remaining part stays the same.
-
Cyber Oliveira over 14 yearsif you want to save one keystroke: ':v' is a synonym to ':g!' :)
-
Marcin over 14 yearsThat saves two keystrokes! Shift, 1. Neat.
-
h7r over 9 yearsAlthough the answer is spot on, the original question was not vim specific. As reference, one can, however, do exactly the same with sed (
sed -e 'g!/^[+-]/d'
).