2016-08-11 113 views
0

因此,我有2個文件具有相同樣式的列出的內容 - 字體ID,字體Def和時間戳。我想採用新字體的第二個文件,並替換具有匹配字體ID的第一個文件的行---使用powershell(沒有數據庫會大大簡化)。用PowerShell替換文本文件的行,基於不同文本文件的行

File2 text line = [FontIDA01] 5,5,5,5,randomtext,11/10/2001 應該替換[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 
     } 
    } 
} 

我是否關閉?

回答

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] }

+0

任何機會你有一個更初學者水平的答案?我沒有任何線索知道你的代碼在做什麼 –

+0

其實,這正是我對你的代碼的想法。愚蠢的我,相信我的代碼是不言自明的......好吧,有人會發布更好的答案,希望。如果有任何幫助,代碼將使用'|'管道逐行處理每個文件。 – wOxxOm

相關問題