Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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?

share|improve this question

3 Answers 3

up vote 8 down vote accepted

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.

share|improve this answer
    
Note that you may want to specify an encoding to Out-File in case some programs choke on UTF-16. –  Joey Feb 21 '11 at 21:13

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.

share|improve this answer

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

findstr /V /C:"abcd" file.txt > file_new.txt
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.