PowerShell - 两个字符之间的小写文本

时间:2018-02-13 08:13:59

标签: powershell character between lowercase

我有很多.txt文件,我需要在两个字符之间小写内容 - 在“%”之后和“;”之前。

下面的代码使文件中的所有内容都是小写的,我只需要在所提到的两个字符之间的所有实例中都这样做。

$path=".\*.txt"
Get-ChildItem $path -Recurse | foreach{    
    (Get-Content $_.FullName).ToLower() | Out-File $_.FullName
}

1 个答案:

答案 0 :(得分:4)

这里使用 regex 的示例替换为回调函数以执行小写:

$path=".\*.txt"
$callback = {  param($match) $match.Groups[1].Value.ToLower() }
$rex = [regex]'(?<=%)(.*)(?=;)'

Get-ChildItem $path -Recurse | ForEach-Object {
        $rex.Replace((Get-Content $_ -raw), $callback) | Out-File $_.FullName
}

<强>解释

正则表达式使用正面的lookbehind来找到%的位置和;位置的前瞻,并在组之间截取所有内容:

enter image description here

被捕获的小组会被传递到callback函数,该函数会在其上调用ToLower()