[英]How can I replace a string in multiple files with a value from a list, sequentially in Powershell?
可以說我有一堆帶有人名的文本文件,它們的內容都是這樣的:
數字
我想根據文件名按順序用 CSV 或文本文件中的值替換“數字”。 CSV 有兩列,名稱和號碼:
Joe 5551011000
Gary 5551011001
Clark 5551011002
所以我想找到名為 Joe 的文本文件,並將“number”替換為“5551011000”,然后找到名為 Gary 的文本文件,並將“number”替換為“5551011001”。
謝謝!
我沒有走得太遠:
Get-ChildItem "C:\test\*.txt" -Recurse | ForEach-Object -Process {
(Get-Content $_) -Replace 'changeme', 'MyValue' | Set-Content $_
}
這讓我在那里聚會,但我不知道如何找到一個特定的文件,然后用與名稱匹配的正確值替換該文件中的“數字”。
我還嘗試了一種不同的方法,手動輸入,它有效,但我需要它是自動化的:
get-childitem c:\Marriott -recurse -include *.txt |
select -expand fullname |
foreach {
$new = Read-Host 'What is the new value you want for ' $_
(Get-Content $_) -replace 'number',$new |
Set-Content $_
}
我會將您的 CSV 轉換為哈希表,然后這就變得非常簡單。
$ReplaceHT = @{}
Import-Csv c:\path\to\file.csv -Delimiter ' ' -Header 'FileName','Number' | ForEach-Object {$ReplaceHT.add($_.FileName,$_.Number)}
Get-ChildItem c:\Marriott -recurse -include *.txt -PipelineVariable 'File'|Where{$_.name -in $ReplaceHT.Keys} |ForEach-Object{
(Get-Content $File.FullName) -replace 'changeme', $ReplaceHT[$File.Name] | Set-Content $File.FullName
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.