【问题标题】:Powershell, delete lines of text from html filePowershell,从html文件中删除文本行
【发布时间】:2015-08-23 03:01:50
【问题描述】:

我在 html 文件中有一些报告。我需要将它们放在excel中并进行一些更改,所以我认为我可以使用powershell预先进行这些更改。有些行在固定位置,有些则不在,所以我需要通过让脚本识别模式来删除它们。

从顶部开始的固定线:12-14,17,19,25-27,30-32,40-42 从底部开始的固定线:3-13、48-60

我需要查找和删除的模式是这样的:

<td align="center">random string</td>
<td align="left">random string</td>
<td align="left">random string</td>
<td align="left">random string</td>
<td align="right">random string</td>

对于我发现的固定线路,我可以这样做:

(gc $maindir\Report23.HTML) | ? {(12..14) -notcontains $_.ReadCount} | out-file $maindir\Report23b.HTML

它在删除第 12-14 行时起作用,但我需要将其余的固定行号放在同一命令中,我似乎不知道怎么做。输出文件的文件大小也是原始文件的两倍,我觉得这很奇怪。我尝试使用 set-content 生成接近原始文件的文件大小,但在某些部分破坏了文本编码。

虽然我不知道如何去识别模式......

【问题讨论】:

    标签: powershell lines


    【解决方案1】:

    输出文件的文件大小是原始文件的两倍,因为原始文件可能是 ASCII 编码的,新文件默认是 Unicode 编码的。试试这个:

    $length = (gc $maindir\Report23.HTML).length
    $rangefrombottom = ($length-60)..($length-48)+($length-13)..($length-3)
    $rangefromtop = 12..14+17,19+25..27+30..32+40..42
    (gc $maindir\Report23.HTML) | ? {$rangefromtop -notcontains $_.ReadCount} | ? {$rangefrombottom -notcontains $_.ReadCount} | out-file -encoding ASCII $maindir\Report23b.HTML
    

    【讨论】:

    • 这对于删除固定行非常有效 :) 关于模式我可以像 (gc $maindir\Report23.HTML) |其中 {$_ -notmatch '.*`n.*...'}...?
    • 我最终创建了一个 excel 宏,但我会将您的答案标记为已接受的答案,因为它涵盖了我试图实现的大部分内容。不过只有一个更正:$rangefrombottom = ($length-59)..($length-47)+($length-12)..($length-2)
    【解决方案2】:

    你不能这样做吗:

    $lines = 12..14
    $lines += 17
    $lines += 25..27
    $lines += 30..32
    $lines += 40..42
    

    然后在 where 子句中使用该数组:

    ? {$lines -notcontains $_.ReadCount} 
    

    【讨论】:

    • 嗯,不,它只替换 12-14。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    相关资源
    最近更新 更多