【发布时间】:2016-03-06 20:49:51
【问题描述】:
我正在尝试仅替换在一堆文本文件中找到的字符串的第一个 出现。我已经为此花费了数小时,但似乎无法修复它。
我无法让它工作。 PowerShell Script to Find and Replace for all Files with a Specific Extension
$text_file_ext = 'txt'
Get-ChildItem $base_dir -Recurse -Include "*.$text_file_ext" |
ForEach-Object { (Get-Content $_.FullName) |
foreach -Begin { $found = $false; $search = 'APPLE' } -Process {
if (! $found -and ($_ -match $search))
{
$_ = $_ -replace $search, ' COFFEE'
$found = $true
}
#$_
Set-Content $_.FullName}
}
我还引用了这个: http://www.adamtheautomator.com/use-powershell-to-do-a-findreplace-on-a-set-of-text-files/
示例文本
Lorem ipsum APPLE dolor sit amet, consectetur adipiscing elit。 Donec a pharetra nisl, vitae APPLE vehicula turpis。 Aenean eleifend bibendum quam,nec dapibus felis viverra ut。 Mauris nec nibh scelerisque, aliquet ligula in, viverra justo。 Interdum et malesuada 在 faucibus 中以 APPLE ante ipsum primis 闻名。
感谢任何建议。
最终版本工作
$search ="APPLE"
$text_file_ext = 'txt'
Get-ChildItem $base_dir -Recurse -Include "*.$text_file_ext" |
ForEach-Object { (Get-Content $_.FullName -Raw) -replace" (.+?)$search(.+)",'$1COFFEE$2'|
Set-content $_.Fullname
}
【问题讨论】:
标签: string powershell search replace