Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all lines (not) matching a regex using Notepad++

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.

like image 525
tmh Avatar asked Dec 24 '15 22:12

tmh


People also ask

How do you replace regex in Notepad?

In all examples, use select Find and Replace (Ctrl + H) to replace all the matches with the desired string or (no string). And also ensure the 'Regular expression' radio button is set. Check that your word wrap is switched off so that you actually see the text get modified.


1 Answers

In the Find dialog, on the Mark tab, you can bookmark lines that match... Then on the menu Search > Bookmark > Remove Unmarked Lines or Remove Bookmarked lines

like image 73
Captain Avatar answered Sep 22 '22 23:09

Captain