Delete all lines in Notepad++ except lines containing a word I need?

I have a text file and want to keep lines started with <Path>, and delete all the other lines.

How can I do it?


Solution 1:

There is an easy way to achieve this. You need to perform 2 steps.

  1. Go to Search menu > Find... > Select "Mark" Tab. Activate regular expressions. Search for ^<Path> (^ is for line start). Don't forget to check "Bookmark lines" and Press "Mark All"

    ==> All Rows you want to keep got a Bookmark

  2. Go to Menu "Search - Bookmark - Remove unmarked lines"

    ==> All lines that aren't Bookmarked are deleted.

Solution 2:

This can actually be done in two steps as of 6.3. I think it can be done earlier than that as I had 5.9 when I first tried it.

Using stema's post as the basis of this answer. There's one less step now. Mark lines and remove unmarked lines. Done. Detailed instructions follow.

  1. Search menu "Find". In the Find dialog, click the "Mark" tab. Activate regular expressions. Search for ^<Path> (^ is for line start). Don't forget to check "Bookmark lines" and Press "Mark All"

    ==> All Rows you want to keep now have a Bookmark

  2. Search Menu -> Bookmark -> Remove Unmarked Lines.

    ==> All NON Bookmarked lines are deleted.

Solution 3:

Clean regex only solution

Two step variant

  1. regex replace

    (?!^.*test.*$)^.+
    

    replace test with your requested text

  2. replace

    [\r\n]{2,}
    

    with \r\n

Single step variant

Use ^(?!<Path>).*\r\n to replace matches with empty string. Generalized version would be ^(?!.*?test).*\r\n. This won't remove empty line at the end of the file. All other lines are removed, including multiple consecutive empty lines.

Explanation:

  1. (?!) is a negative look up. ^.*test.*$ selects the whole line that contains the requested text.

  2. [\r\n]{2,} matches any \r\n that occurs more then once this is Windows New line. if you have Linux or another operating system you might need to mess with this. the second is to replace it with one return line.

Solution 4:

It seems to me that the easiest way is to just use the "Find All in Current Document" feature and then either copy the results into a new file or select all and replace in the current one.

This would find all lines containing your text and list them at the bottom. Just right click on the search result and copy / paste.

Solution 5:

Go to menu Search -> Find... -> Activate regular expressions. Search for "^Path" (^ is for line start).

Click on the "Find all in Current Document" button.

The "Find result" window will appear with all the lines the the pattern. Select copy/paste them to a new tab in Notepad++.

In this new tab, got to: menu Search -> Replace... -> Activate regular expressions.

In the "Find what:" field, use the pattern: "Line \d+: ". Leave the "Replace with:" field blank.

Click on the "Replace all" button.