我需要一段powershell-code来搜索和替换文本文件中的某个字符串.在我的例子中,我想用'24 -06-2016'替换23-06-2016'.下面的脚本完成这项工作:
$original_file = 'file.old'
$destination_file = 'file.new'
(Get-Content $original_file) | Foreach-Object {
$_ -replace '23-06-2016', '24-06-2016' `
} | Out-File -encoding default $destination_file
Run Code Online (Sandbox Code Playgroud)
随着搜索/替换字符串更改,我想循环遍历可能如下所示的日期数组:
$dates = @("23-06-2016","24-06-2016","27-06-2016")
Run Code Online (Sandbox Code Playgroud)
我试过用了
$original_file = 'file.old'
$destination_file = 'file.new'
foreach ($date in $dates) {
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'date', 'date++' `
} | Out-File -encoding default $destination_file
}
Run Code Online (Sandbox Code Playgroud)
在第一步中,'23 -06-2016'的日期应该被'24 -06-2016'取代,而在第二步中,'24 -06-2016'的日期应该被'27 -06-2016取代".
由于我的剧本不起作用,我正在寻求一些建议.
您$date在foreach循环中使用您的实例变量,然后将其引用为'date',这只是一个字符串.即使您使用'$date'它也行不通,因为单引号字符串不会扩展变量.
此外,$date不是数字,所以date++即使它被引用为变量也不会做任何事情$date++.更进一步,$var++在递增之前返回原始值,因此您将引用相同的日期(而不是前缀版本++$var).
在foreach循环中,在大多数情况下,引用其他元素并不是很实际.
相反,你可以使用for循环:
for ($i = 0; $i -lt $dates.Count ; $i++) {
$find = $dates[$i]
$rep = $dates[$i+1]
}
Run Code Online (Sandbox Code Playgroud)
这不一定是最明确的方法.
[hashtable]使用日期作为关键字,并将替换日期作为值,您可能会更好.当然,你要复制一些日期作为价值和关键,但我想我宁愿有清晰度:
$dates = @{
"23-06-2016" = "24-06-2016"
"24-06-2016" = "27-06-2016"
}
foreach ($pair in $dates.GetEnumerator()) {
(Get-Content $original_file) | Foreach-Object {
$_ -replace $pair.Key, $pair.Value
} | Out-File -encoding default $destination_file
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24523 次 |
| 最近记录: |