Stripping lines from text file with Powershell

I am trying to remove specific lines from a text file. The text file is just a list and I want to remove specific entries if they are present. So what I have is this:

$f=${path_to_file}
for($i = 0; $i -le $f.length; $i++)
{
    if ($f[$i] -eq "text_to_be_deleted")
    {
        $f[$i]=$null
    }
}
${path_to_file}=$f

The problem is that this is stripping out all the carriage returns from the text file. I tried the following:

(type path_to_file) -notmatch "text_to_be_deleted" | out-file path_to_file

The problem with that command is that I may have a string such as "abc", "abcd", or "abcde". If I have "abc" in the quotes", it deletes any line containing "abc", not just an exact match. I really suck at regular expressions so I couldn't figure out how to specify an exactly this string.

Any suggestions on how to do this?


This can be accomplished with a one-liner:

(type path_to_file) -notmatch "^text to be deleted$" | out-file path_to_file

Note that the ^ means 'start of the line' and the $ means end of the line.


If you don't mind using non-PowerShell tools:

findstr /V /C:"abcd" file.txt > file_new.txt