本帖最后由 flashercs 于 2020-2-25 00:05 编辑
回复 7# zouming16888
自动识别utf8编码文本,无论是否带有bom,都能让修改后的文本与原文本保持一致.
即:utf8bom -> utf8bom ; utf8-nobom -> utf8-nobom- <#*,:&cls
- @echo off
- pushd "%~dp0"
- powershell -NoProfile -ExecutionPolicy RemoteSigned -Command ". ([ScriptBlock]::Create((Get-Content -LiteralPath \"%~0\" -ReadCount 0 | Out-String ))) "
- popd
- pause
- exit /b
- #>
- # utf8-bom 与 utf8-nobom 编码自适应修改文本内容; bom或nobom保持与原文本不变.
- # $oldstr -> $newstr
- $oldstr = 'www.中文Hello.com'
- $newstr = 'www.qq.com'
-
- $iso88591 = [System.Text.Encoding]::GetEncoding('iso-8859-1')
- $utf8 = [System.Text.Encoding]::UTF8
- $oldstr = $iso88591.GetString($utf8.GetBytes($oldstr))
- $newstr = $iso88591.GetString($utf8.GetBytes($newstr))
- Get-ChildItem -Path . -Filter * -Include *.txt, *.php, *.jsp, *.ini, *.html, *.mxl, *.css, *.js, *.tpl, *.json, *.config -Recurse | ForEach-Object -Process {
- if (!$_.PSIsContainer) {
- $filestream = $_.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::Read)
- $sr = New-Object System.IO.StreamReader -ArgumentList @($filestream, $iso88591, $false, 64000, $true)
- $sw = New-Object System.IO.StreamWriter -ArgumentList @($filestream, $iso88591)
- $str = $sr.ReadToEnd().Replace($oldstr, $newstr)
- [void]$filestream.Seek(0, [System.IO.SeekOrigin]::Begin)
- $sw.Write($str)
- [void]$filestream.SetLength($filestream.Position)
- $sr.Dispose()
- $sw.Dispose()
- $filestream.Dispose()
- }
- }
复制代码
|