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:

globally 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 delete those lines.

Solution 2

sed -e '/^[^+-]/d'

Share:
17,474
mager
Author by

mager

Updated on June 19, 2022

Comments

  • mager
    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
    SourceSeeker over 14 years
    You definitely need another caret and may not need "e" or quotes. This works for me: grep ^[^+-]
  • Joy Dutta
    Joy Dutta over 14 years
    Agree 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
    Cyber Oliveira over 14 years
    if you want to save one keystroke: ':v' is a synonym to ':g!' :)
  • Marcin
    Marcin over 14 years
    That saves two keystrokes! Shift, 1. Neat.
  • h7r
    h7r over 9 years
    Although 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').