Scroll through the file and delete some lines with different text
I am trying to loop through a file and delete lines that are not needed. Lines in the file have a unique number that does not change. What I have so far is not deleting the line in the foreach loop, but individually.
$FSEFiles=get-childitem E:\FSE*.txt
foreach ($file in $FSEFiles)
{
try
{
(Get-Content $file.PSPath) |
Foreach-Object { Where-Object { $_ -notmatch "15987@" } } |
Foreach-Object { Where-Object { $_ -notmatch "16422@" } } |
#Foreach-Object {Where-Object { $_ -notmatch "17526@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17527@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17528@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17530@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17531@"}} |
#Foreach-Object {Where-Object { $_ -notmatch "17532@"}} |
Set-Content $file.PSPath
write-host $file updated
}
catch
{
write-host Error editing $file
}
}
Am I missing something that will allow this loop to run on every line?
+3
source to share
1 answer
Since you are already using regex you can combine all these requirements into one nice regex string
$regex = "(15987@|16422@|1752[6-8]@|1753[0-2]@)"
$data = Get-Content $file.PSPath
$data | Where-Object{$_ -notmatch $regex} | Set-Content $file.PSPath
Perhaps something like this will overpower it. Not very tested but should work. That you may have worked locally, but something seems to be wrong with the combination foreach
and where
(hence the question), but it would be overkill to try and resolve what I think.
+3
source to share