【问题标题】:Parsing html tag link with Powershell使用 Powershell 解析 html 标签链接
【发布时间】:2021-06-16 15:59:02
【问题描述】:

我想将第一个标签(链接)的内容复制到接下来的 2 个标签中:

<link rel="canonical" href="https://website.com/en/america.html" />

<meta property="og:url" content="https:/something-better/rosrr.html"/>

"@id": "https://distrinct.com/stiintess-pomei.html"

输出:

<link rel="canonical" href="https://website.com/en/america.html" />

<meta property="og:url" content="https://website.com/en/america.html"/>

"@id": "https://website.com/en/america.html"

我真的不知道为什么我的 Powershell 代码无法正常工作:

$sourcedir = "C:\Folder1\"
$resultsdir = "C:\Folder1\"

Get-ChildItem -Path $sourcedir -Filter *.html | ForEach-Object {
    $content = Get-Content -Path $_.FullName -Raw
    $replaceValue = (Select-String -InputObject $content -Pattern '(?<=<link rel="canonical" href=").+(?=" />)').Matches.Value
    $content = $content -replace '(<meta property="og:url" content=").+("/>)',$replaceValue
    $content = $content -replace '("@id": ").+(")',$replaceValue
    Set-Content -Path $resultsdir\$($_.name) $content
}

这是我得到的,而不是我想要的输出:

【问题讨论】:

    标签: powershell powershell-3.0 azure-powershell powershell-4.0


    【解决方案1】:

    我想通了。要使用正则表达式在 Powershell 中进行解析,必须使用相同的“开始”和相同的“停止”。而且你必须注意正则表达式:

    $sourcedir = "C:\Folder1\"
    $resultsdir = "C:\Folder1\"
    
    Get-ChildItem -Path $sourcedir -Filter *.html | ForEach-Object {
        $content = Get-Content -Path $_.FullName -Raw
        $replaceValue = (Select-String -InputObject $content -Pattern '(?<=<link rel="canonical" href=").*(")').Matches.Value
        $content = $content -replace '(?<=<meta property="og:url" content=").*(")',$replaceValue
        $content = $content -replace '(?<="@id": ").*(")',$replaceValue
        Set-Content -Path $resultsdir\$($_.name) $content
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 2016-01-28
      • 2010-09-12
      • 1970-01-01
      • 2012-11-14
      • 2016-02-14
      • 2014-04-25
      相关资源
      最近更新 更多