23

How to delete all lines matching or not matching a regex in Notepad++?

In Vim, I'd do the following to delete all matching lines:

:g/regex/d

And to delete all non matching lines:

:!g/regex/d

I'm looking for these commands' equivalent in Notepad++.

As also explained in "Notepad++ - delete all lines with certain text", I usually go for the approach of blanking the matching lines and deleting the blank lines afterwards. Is there a simpler way?


As per this answer, versions of Notepad++ >= 6.0 support matching line breaks in regex, thus allowing to delete whole lines directly without creating blank lines first. The following pattern should remove all lines containing "foobar" when replaced with an empty string:

^.*foobar.*\r\n

Now, as discussed in "Regular expression to match a line that doesn't contain a word?", negating regular expressions isn't exactly straightforward. Deleting lines in Notepad++ which do not contain "foobar" would require the following pattern:

^((?!foobar).)*\r\n

Because that's a quite complicated command to type just for removing lines which don't contain a word (or possibly more complex expression), I wonder if there is an easier solution.

3
  • Are you interested in 1-step solution only? There is another solution, an unroll-the-loop one: ^[^f\n]*(?:f(?!oobar)[^f\n]*)*(?:\R|$), but again it might look "complicated". Commented Dec 24, 2015 at 22:23
  • I'm interested in the solution which takes the fewest keystrokes/clicks. :) Commented Dec 24, 2015 at 22:25
  • 1
    Then, I guess, you have a solution below. Commented Dec 24, 2015 at 22:28

1 Answer 1

59

In the Find (Ctrl + F or Search > Find) dialog, on the Mark tab, you can Bookmark lines that match.

mark ui

Then use the menu item Search > Bookmark > Remove Non-Bookmarked Lines or Remove Bookmarked lines.

menu layout

Sign up to request clarification or add additional context in comments.

7 Comments

This is probably fastest way to do it in Notepad++. :)
yeah that's a great way to do it!
I have matched some part of each line so this doesnt work for me
for those finding this now, you need to check "Bookmark line" checkbox for this to work. @UmairAyub
If I could upvote twice I would! Super easy to do, but I always forget that the Remove Unmarked Lines is inside the Search menu
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.