Windows Powershell替换文件夹中文本文件的一组字符
使用代码替换文件夹中文本文件的一组字符。有一种方法可以为文件夹中的所有文件执行此操作。我正在使用Windows 7操作系统和Powershell版本3.附加我拥有的代码。问题是,当我运行代码(New_NOV_1995.txt)时它会创建一个新文件,但它不会像代码中所述那样更改新文件中的任何字符。非常感谢帮助。Windows Powershell替换文件夹中文本文件的一组字符
$lookupTable = @{
'¿' = '|'
'Ù' = '|'
'À' = '|'
'Ú' = '|'
'³' = '|'
'Ä' = '-'
}
$original_file = 'C:\FilePath\NOV_1995.txt'
$destination_file = 'C:\FilePath\NOV_1995_NEW.txt'
Get-Content -Path $original_file | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key)
{
$line = $line -replace $_.Key, $_.Value
}
}
$line
} | Set-Content -Path $destination_file
在下面的例子中,我假设H:\ Replace_String是一个目录。在你的代码中,你没有反斜杠,所以它只会选择H:的根目录中的文件。
$configFiles = Get-ChildItem -path H:\Replace_String\*.txt
foreach ($file in $configFiles)
{
(Get-Content $file) |
Foreach-Object { $_ -replace "Cat", "New_Cat" } |
Foreach-Object { $_ -replace "Dog", "New_Dog" } |
Set-Content $file
}
Thx Tony ...此代码给出错误:路径中找不到位置参数。 –
它适用于我 - 唯一不同的是我使用C:而不是H :.我正在运行PowerShell 4.0,所以如果你正在运行的东西可能会有所作为。我谷歌“位置参数无法找到路径”,它出现零点击。你是否包含完整的错误信息?你可以尝试在H:\ Replace_String \ *。txt周围加引号,但我不知道还有什么可以试试我的头顶。 –
“在H:\ Replace_string \
Tony Hinkle提出的(原始)答案需要另一个循环。原因是Get-Content
产生一个数组。每行代表数组的一个元素。
$configFiles = Get-ChildItem -path 'H:\Replace_String\*.txt'
foreach ($file in $configFiles){
$output = @()
$content = Get-Content $file
foreach ($line in $content) {
$line = $content.Replace("Cat", "New_Cat")
$line = $content.Replace("Dog", "New_Dog")
$output += $line
}
$output | Set-Content -Path $file
}
编辑:我注意到Tony Hinkle的回答在我发布时已经修改。他通过一个管道发送一切,我将数组存储在一个变量中,然后循环。管道方法可能更有效率。对于数组中的每个元素,使用第二个循环的变量更容易修改,而不仅仅是两次替换。
在第一行中使用'Get-ChildItem'而不是'Get-Content'。 –