delete everything after keyword

青春壹個敷衍的年華 提交于 2019-12-11 18:19:13

问题


I try to merge to files with Compare-Object and I got a file like this:

Number=5
Example=4
Track=1000
Date=07/08/2018 19:51:16
MatCaissierePDAAssoc=
NomImpPDAAssoc=
TpeForceLectPan=0
Number=1
Example=1
Track=0
Date=01/01/1999

You can see it repeats with Number=1. Except with a different value. I would like to delete everything (everything means not only "= 1") after my keyword "Number" and my keyword itself.

This is what I did so far:

$files = Get-ChildItem "D:\all"
foreach ($file in $files) {
    $name = dir $file.FullName | select -ExpandProperty Name

    Compare-Object -ReferenceObject (Get-Content D:\original\test.ini) -DifferenceObject (Get-Content $file.FullName) -PassThru |
        Out-File ('D:\output\' + $name)
}

And I would like to delete all lines with "Track" and "Date".

My Result should look like this:

Number=5
Example=4
MatCaissierePDAAssoc=
NomImpPDAAssoc=
TpeForceLectPan=0

In fact I need something to delete double keys in my file.


回答1:


This might help:

# read existing file
$fileContent = Get-Content C:\tmp\so01.txt

# iterate over lines
foreach($line in $fileContent) {
  # filter lines beginning with 'Track' or 'Number'
  if((-not $line.StartsWith('Track')) -and (-not $line.StartsWith('Number'))) {
    # output lines to new file
    $line | Add-Content C:\tmp\so02.txt
  }
}

Content of C:\tmp\so02.txt:

Example=4
Date=07/08/2018 19:51:16
MatCaissierePDAAssoc=
NomImpPDAAssoc=
TpeForceLectPan=0
Example=1
Date=01/01/1999


来源:https://stackoverflow.com/questions/51898328/delete-everything-after-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!