gpt4 book ai didi

powershell - 在 Powershell 中替换多个字符串的正确语法

转载 作者:行者123 更新时间:2023-12-03 11:23:42 24 4
gpt4 key购买 nike

我们有一个包含 3000 多个 HTML 文件的目录,这些文件正在迁移到共享点站点,我们需要清理一些数据。

具体情况:

  • 大约 1/3 的文件包含 XML header <?xml version="1.0" encoding="utf-8"?>该共享点不喜欢。我们计划只删除该标题行。
  • 每个文件都有“HOME”的javascript参数,指向两个备用的相对主页链接foo1.htmfoo.htm .我们想将两者都更改为 http:\\sharepoint.site\home.aspx 的绝对链接
  • 每个文件还有一个 javascript 链接参数“Show”,我们只想通过将其更改为 '' 来隐藏它。 .

  • 到目前为止,这是我的功能:
    function scrubXMLHeader {
    $srcfiles = Get-ChildItem $backupGuidePath -filter "*htm.*"
    $srcfilecount = (Get-ChildItem $backupGuidePath).Count
    $selfilecount = $srcfiles.Count
    # Input and Ouput Path variables
    $sourcePath = $backupGuidePath
    $destinationPath = $workScrubPath
    "Input From: $($sourcePath)" | Log $messagLog -echo
    " Output To: $($destinationPath)" | Log $messageLog -echo
    #
    $temp01 = Get-ChildItem $sourcePath -filter "*.htm"
    foreach($file in $temp01)
    {
    $outfile = $destinationPath + $file
    $content = Get-Content $file.Fullname | ? {$_ -notmatch "<\?xml[^>]+>" }
    Set-Content -path $outfile -Force -Value $content
    }
    }

    我想为每个文档添加以下两个编辑:
    -replace '("foo.htm", "", ">", "Home", "foo1.htm")', '("http:\\sharepoint.site\home.aspx", "", ">", "Home", "http:\\sharepoint.site\home.aspx")
    -replace 'addButton("show",BTN_TEXT,"Show","","","","",0,0,"","","");', ''

    我不确定如何将它们组合成一个语句,所以我打开文件、执行更改、保存和关闭文件,而不是三个单独的打开-编辑-保存/关闭事务。我也不确定,对于所有引号和逗号,转义这些字符的最佳方法,或者整个字符串周围的单引号是否足够。

    了解“ asking regexes to parse arbitrary HTML is like asking Paris Hilton to write an operating system, it's sometimes appropriate to parse a limited, known set of HTML ”,但我的工具集仅限于 PowerShell,我试图了解添加这两个 -replace 的最佳方法。线到现有 $content变量...在花括号内用逗号分隔?互相输送?

    以下这些是最佳策略吗?或者有什么更好的吗?
    $content = Get-Content $file.Fullname | ? {$_ -notmatch "<\?xml[^>]+>", 
    -replace '("foo.htm", "", ">", "Home", "foo1.htm")', '("http:\\sharepoint.site\home.aspx", "", ">", "Home", "http:\\sharepoint.site\home.aspx"),
    -replace 'addButton("show",BTN_TEXT,"Show","","","","",0,0,"","","");', '' }

    最佳答案

    如果我正确阅读了问题,我认为这可能会满足您的要求:

    $Regex0 = '<?xml version="1.0" encoding="utf-8"?> '

    $Regex1 = '("foo.htm", "", ">", "Home", "foo1.htm")'
    $Replace1 = '("http:\\sharepoint.site\home.aspx", "", ">", "Home", "http:\\sharepoint.site\home.aspx")'

    $Regex2 = 'addButton("show",BTN_TEXT,"Show","","","","",0,0,"","","");'


    foreach($file in $temp01)
    {
    $outfile = $destinationPath + $file
    (Get-Content $file.Fullname) -notmatch $Regex0,'' -replace $Regex1,$Replace1 -replace $Regex2,'' |
    Set-Content -path $outfile -Force -Value $content
    }

    关于powershell - 在 Powershell 中替换多个字符串的正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20690282/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com