Remove multiple predefined lines in text file with powershell

When you need to remove multiple lines from a text file without a time consuming process. Powershell on Windows allows you to do this in a single command.

If you ever run into a problem where you need to remove certain lines from a text file but going through every line isn’t an option or time consuming. Powershell on Windows allows you to do this with a simple command that will let you remove the lines you don’t need.

Here, we are going to create two files;

  • remove.txt contains the lines you want to remove
  • original.txt is where you want to remove the lines

We are going to include these two files in the same folder to make it easy to run the commands. Then open up a powershell window on the current path. You can do this by typing powershell on the navigation bar on the explorer window.

Window explorer window with original and remove text files.
Before the removal of predefined text from the original file.

On the powershell, run this command for the process to start. This command will take the lines from the remove.txt, search it inside original.txt and creates a list of new lines without the ones it found. It will then create a new file new.txt with the lines removed.

findstr /l /x /v /i /g:remove.txt original.txt > new.txt

Findstr is a powershell application that searches for patterns of text in files. The parameters filter out the contents from remove.txt while going through original.txt. The “>” writes the content from the findstr command to the new.txt file.

  • /l Processes search strings literally.
  • /x Prints lines that match exactly.
  • /v Prints only lines that don’t contain a match.
  • /i Ignore the case of the characters when searching for the string.
  • /g:<file> Gets search strings from the specified file.

The `new.txt` file is the one with the filtered results. And you can use it as you please.

An screenshot showing the text files; original, remove, and new. new is the one generated by the command
An screenshot showing the text files. new.txt is the generated one

Recently I ran into a problem with the uBlock filter rules. There were many rules that I had added, as suggested by an extension called LocalCDN. It suggests a list of filter rules you can add to the list so it can serve content locally. It was good until I saw the extension stats. Probably because I rarely visit a huge range of websites on the daily. So, after I copied the lines LocalCDN suggested to remove.txt file, I used this command to get rid of all the LocalCDN references in my filter list.