且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell 替换字符串中的字符

更新时间:2023-02-03 09:38:48

试试这个:

$regex = [regex]'(.).{3}(.{4}).{2}(.{6}).{5}(.{3}).(.+)'
$replace = '$1...$2..$3.....$4.$5'

('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
 '12345678901234567890123456') -Replace $regex,$replace

A...EFGH..KLMNOP.....VWX.Z
1...5678..123456.....234.6

-replace 操作符单次操作比 string.replace() 慢,但优点是可以对字符串数组进行操作,比 string 方法加 foreach 循环要快.

The -replace operator is slower than string.replace() for a single operation, but has the advantage of being able to operate on an array of strings, which is faster than the string method plus a foreach loop.

这是一个示例实现(需要 V4):

Here's a sample implementation (requires V4):

$regex =  [regex]'(.).{3}(.{4}).{2}(.{6}).{5}(.{3}).(.+)'
$replace = '$1...$2..$3.....$4.$5'

filter fix-file {
 $_ -replace $regex,$replace | 
 add-content "c:\mynewfiles\$($file.name)"
}

get-childitem c:\myfiles\*.txt -PipelineVariable file |
 get-content -ReadCount 1000 | fix-file 

如果你想使用掩码方法,你可以从中生成 $regex 和 $replace :

If you want to use the mask method, you can generate $regex and $replace from that:

$mask  = '-...----..------.....---.-'

 $regex = [regex]($mask -replace '(-+)','($1)').replace('-','.')

 $replace = 
 ([char[]]($mask -replace '-+','-') |
  foreach {$i=1}{if ($_ -eq '.'){$_} else {'$'+$i++}} {}) -join ''

$regex.ToString()
$replace

(.)...(....)..(......).....(...).(.)
$1...$2..$3.....$4.$5