[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖
(1)把下面的批处理脚本保存编码格式为utf8-nobom,一定不能用 记事本编辑.
(2)所有处理的文件一律改用utf8编码.
  1. ::替换内容
  2. rem 定义要替换的新旧字符串
  3. chcp 65001
  4. cd %cd%
  5. set strOld=www.baidu.com
  6. set strNew=www.qq.com
  7. for /f "tokens=*" %%i in ('dir *.txt,*.php,*.jsp,*.ini,*.html,*.mxl,*.css,*.js,*.tpl,*.json,*.config /S /B') do (
  8.     set "var=%%i"
  9.     setlocal enabledelayedexpansion
  10.     if not !var!.==. (
  11.     for /f "usebackq tokens=*" %%j in ("!var!") do (
  12.         set "tmp=%%j"
  13.         if not !tmp!.==. (
  14.           set "tmp=!tmp:%strOld%=%strNew%!"
  15.           echo !tmp!>>temp.txt
  16.         )
  17.     )
  18.     move temp.txt "!var!"
  19.     endlocal
  20.     )
  21. )
复制代码
微信:flashercs
QQ:49908356

TOP

本帖最后由 flashercs 于 2020-2-25 00:05 编辑

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

TOP

返回列表