5

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?

3 Answers 3

7

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.

1
  • Note that you may want to specify an encoding to Out-File in case some programs choke on UTF-16.
    – Joey
    Feb 21, 2011 at 21:13
2

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

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

You've got most of it.

$f=${path_to_file}
for($i = 0; $i -le $f.length; $i++)
{
    ## If NOT EQUAL to text-to-be-deleted, print to file
    if ($f[$i] -ne "text_to_be_deleted")
    {
        ## write to file, preserving carriage returns.
        out-file -filepath ${path_to_file} -InputObject $f[$i] -append
    }
}

It uses out-file in a different way than you are, but it should preserve CR's.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .