dffdsfdfsd
dffdsfdfsd

Reputation: 31

Delete line if it includes a specific string

I have a text file where it will say the computer name and current date they logged in.

04/10/2017,  "PC1"
04/10/2017,  "PC4"
05/10/2017,  "PC3"
09/10/2017,  "PC2"

I'm having issues trying to run a script that will look for any line that includes "PC2" and delete that line :

get-content "c:\file.csv" | %{if($_ -match "PC2"){$_ -replace $_, ""}} | set-content c:\file.csv

Upvotes: 1

Views: 8484

Answers (2)

Maximilian Burszley
Maximilian Burszley

Reputation: 19644

(Get-Content -Path 'C:\File.csv') |
    Where-Object { $_ -notlike '*PC2*' } |
    Set-Content -Path 'C:\File.csv'

Here you go. This utilizes an easier-to-understand wildcard comparison operator and just filters out the lines that have the matched string.

Upvotes: 2

Vincent K
Vincent K

Reputation: 1346

(Get-Content 'C:\File.csv') -notmatch 'PC2' | Set-Content 'C:\File1.csv'

You can also use regex

File extension is csv

Import-Csv 'C:\File.csv' -Header Logged,Computer | 
       where {$_.Computer -ne 'PC2'} |
              Export-Csv 'C:\File.csv' -NoClobber -NoTypeInformation

Upvotes: 4

Related Questions