File 基于不同文本文件的行,使用powershell替换文本文件的行

File 基于不同文本文件的行,使用powershell替换文本文件的行,file,powershell,text,replace,edit,File,Powershell,Text,Replace,Edit,因此,我有两个文件具有相同样式的列出的内容-字体ID、字体Def和时间戳。我想使用第二个新字体文件,并替换第一个文件中具有匹配字体ID的行——使用powershell(没有更简单的数据库) File2文本行=[fontid01]5,5,5,5,randomtext,11/10/2001 应替换文件1中[FontIDA01]匹配的行,并将5,5,5替换为6,6,6,6,将日期替换为该行上的日期 $content = Get-Content $fileSelected #(path chosen b

因此,我有两个文件具有相同样式的列出的内容-字体ID、字体Def和时间戳。我想使用第二个新字体文件,并替换第一个文件中具有匹配字体ID的行——使用powershell(没有更简单的数据库)

File2文本行=[fontid01]5,5,5,5,randomtext,11/10/2001 应替换文件1中[FontIDA01]匹配的行,并将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 
      }
   }
}

我离你很近吗

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

# 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
或regexp matching:
if($--match'(.+?)([\d,]+)等){$id=$matches[0]}

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

# 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
或regexp matching:
if($\u-match'(.+?)([\d,]+)等){$id=$matches[0]}

有没有可能获得更初级的答案?我不知道你的代码实际上在做什么,这正是我对你的代码的想法。愚蠢的我,相信我的代码是不言自明的。。。希望有人能给出更好的答案。如果有帮助,代码会使用
|
管道逐行处理每个文件。您有没有可能找到更初级的答案?我不知道你的代码实际上在做什么,这正是我对你的代码的想法。愚蠢的我,相信我的代码是不言自明的。。。希望有人能给出更好的答案。如果有帮助,代码将使用
|
管道逐行处理每个文件。