删除文本文件中包含字符串的行,然后删除接下来的两行

时间:2019-02-25 18:45:17

标签: powershell

我尝试了Remove a line of text and the next 0 to 5 lines with powershell 2,但是删除了脚本中的所有内容。

我正在构建一个PowerShell脚本来解析LMtools输出。 我有一条线可以清除所有未使用的东西

$body = (($body -split "`n") |
        Where-Object {$_ -notmatch 'Total of 0 licenses in use'}) -join "`n"

我不需要查看正在使用的软件包,因为以下两个许可证准确显示了正在使用的软件包。

我需要删除“包装用户”行和以下两行。

所以这个:

Users of Package: Autodesk AutoCAD:  (Total of 1 license issued;  Total of 1 license in use)
  "Package: Autodesk AutoCAD" v1.000, vendor: adskflex, expiry: permanent(no expiration date)
    UserH ybw-w7-15021 ybw-w7-15021 (v1.000) (licenseserver/27000 490), start Mon 2/25 10:38
Users of Package: AutoCAD - including specialized toolsets:  (Total of 1 license issued;  Total of 1 license in use)
  "Package: AutoCAD - including specialized toolsets" v1.000, vendor: adskflex, expiry: 15-feb-2020
    UserA DC18007-W10 DC18007-W10 (v1.000) (licenseserver/27000 114), start Mon 2/25 10:50
Users of Autodesk AutoCAD 2017:  (Total of 4 licenses issued;  Total of 1 license in use)
  "Autodesk AutoCAD 2017" v1.000, vendor: adskflex, expiry: 15-feb-2020
    UserA DC18007-W10 DC18007-W10 (v1.0) (licenseserver/27000 214), start Mon 2/25 10:50
Users of Autodesk AutoCAD 2015:  (Total of 4 licenses issued;  Total of 1 license in use)
  "Autodesk AutoCAD 2015" v1.000, vendor: adskflex, expiry: permanent(no expiration date)
    UserH DCw7-15021 DCw7-15021 (v1.0) (licenseserver/27000 390), start Mon 2/25 10:38

就是这样:

Users of Autodesk AutoCAD 2017:  (Total of 4 licenses issued;  Total of 1 license in use)
  "Autodesk AutoCAD 2017" v1.000, vendor: adskflex, expiry: 15-feb-2020
    UserA DC18007-W10 DC18007-W10 (v1.0) (licenseserver/27000 214), start Mon 2/25 10:50
Users of Autodesk AutoCAD 2015:  (Total of 4 licenses issued;  Total of 1 license in use)
  "Autodesk AutoCAD 2015" v1.000, vendor: adskflex, expiry: permanent(no expiration date)
    UserH DCw7-15021 DCw7-15021 (v1.0) (licenseserver/27000 390), start Mon 2/25 10:38

1 个答案:

答案 0 :(得分:1)

您可以逐行阅读输入内容,然后跳过与“软件包用户:”相匹配的行以及接下来的两行。但是,由于您的整个输入文件似乎由3行组成,因此我可能会使用Select-String并使用否定的超前断言。

$pattern = '^Users of (?!Package:)'
Get-Content 'input.txt' | Select-String $pattern -Context 0,2 | ForEach-Object {
    $_.Line
    $_.Context.PostContext
} | Set-Content 'output.txt'

该模式在一行(^)的开头与字符串“ Users of”匹配,但后跟字符串“ Package:”。

使用-Context 0,2包含随后的两条匹配的输入行。