【问题标题】:Replacing lines of a text file with powershell, based on lines of a different text file根据不同文本文件的行,用 powershell 替换文本文件的行
【发布时间】:2016-08-11 20:10:08
【问题描述】:

所以我有 2 个具有相同样式的列出内容的文件 - 字体 ID、字体定义和时间戳。我想获取新字体的第二个文件,并使用 powershell 替换第一个文件中具有匹配字体 ID 的行(没有数据库会更容易)。

File2 文本行 = [FontIDA01] 5,5,5,5,随机文本,2001 年 11 月 10 日 应替换 [FontIDA01] 匹配的 File1 行,并将 5,5,5,5 替换为 6,6,6,6,并将日期替换为该行的日期。

$content = Get-Content $fileSelected #(path chosen by user)
$masterContent = Get-Content $masterContentPath #(hardcoded path)
foreach($line in content)
{
   $fontID = $line.SubString($startFontID, $endFontID)#this just sets font id = 23jkK instead of [23jkK]
   foreach($masterLine in $masterContent)
   {
      if ($masterLine.Contains($fontID))
      {
         $masterContent -replace $masterLine, $line where-Object{$_.Name -contains $fontID} | Set-Content $masterContent -raw 
      }
   }
}

我什至接近吗?

【问题讨论】:

    标签: file powershell text replace edit


    【解决方案1】:

    在字典中收集新数据并将其用于替换:

    # get new data in a dictionary
    $newData = @{}
    Get-Content 2.txt | %{
        $parts = $_ -split ' '
        $newData[$parts[0]] = @{numbers=$parts[1]; date=$parts[3]}
    }
    
    #patch original data using the new data dictionary
    Get-Content 1.txt | %{
        $parts = $_ -split ' '
        $id = $parts[0]
        $new = $newData[$id]
        if ($new) {
            $id, $new.numbers, $parts[2], $new.date -join ' '
        } else {
            $_
        }
    } | Out-File 3.txt -Encoding utf8
    

    此代码假设字段由空格分隔,因此如果不是这种情况,您将不得不使用其他方法来提取部分,例如 Select-String 或正则表达式匹配:if ($_ -match '(.+?) ([\d,]+) and so on') { $id = $matches[0] }

    【讨论】:

    • 你有没有机会得到更初级的答案?我不知道你的代码在做什么
    • 其实,这正是我对你的代码的想法。愚蠢的我,相信我的代码是不言自明的......好吧,希望有人会发布更好的答案。如果有任何帮助,代码将使用| 管道逐行处理每个文件。
    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    相关资源
    最近更新 更多