Board logo

标题: [文本处理] 已解决:批处理替换4个文件中相同的内容 [打印本页]

作者: 大地    时间: 2023-1-21 12:25     标题: 已解决:批处理替换4个文件中相同的内容

本帖最后由 大地 于 2023-1-21 19:39 编辑

大年30  各位老师好   我还在不断学习中    ,如果在同一文件下,有4个不同文件txt,如何同时替换4个文件中相同的字符内容,怎 么修改一下,谢谢!!!
下面这个试了一直没成功
  1. cd %~dp0
  2. @echo off
  3. setlocal enabledelayedexpansion
  4. set source1=小芳
  5. set replaced1=王小芳
  6. for /f "delims=" %%a in ('dir /a-d /b /s *.txt') do (
  7. pushd "%%~dpa"
  8. (for /f "delims=" %%b in ('type "%%a"') do (
  9. set "line=%%b"
  10. set "line=!line:%source1%=%replaced1%!"
  11. echo,!line!
  12. ))>"%%~nxa.txt"
  13. move /y "~nxa.txt" "%%~nxa"
  14. popd
  15. )
复制代码

作者: pd1    时间: 2023-1-21 14:31

  1. <# :
  2. @echo off&powershell -NoProfile -ExecutionPolicy bypass "Get-Content -literal '%~f0' |Out-String|Invoke-Expression"&pause
  3. #>
  4. ls -Recurse *.txt|%{[IO.File]::WriteAllText($_.FullName,[IO.File]::ReadAllText($_.FullName).replace("小芳","王小芳"))}
复制代码

作者: 大地    时间: 2023-1-21 14:44

本帖最后由 大地 于 2023-1-21 14:45 编辑

回复 2# pd1
老师您好   能不能用DOS内置命令写   我多数系统是精简版,VB不全的,谢谢  新年快乐  心想事成!!
作者: 77七    时间: 2023-1-21 16:22

  1. move /y "%%~nxa.txt" "%%~nxa"
复制代码

倒数第三行,改成这样试试
作者: Batcher    时间: 2023-1-21 17:07

回复 3# 大地


    2楼代码需要PowerShell,不需要VB的。
作者: Batcher    时间: 2023-1-21 17:12

回复 1# 大地
  1. @echo off
  2. cd /d "%~dp0"
  3. setlocal enabledelayedexpansion
  4. set "source1=小芳"
  5. set "replaced1=王小芳"
  6. for /f "delims=" %%a in ('dir /a-d /b /s *.txt') do (
  7.     pushd "%%~dpa"
  8.     (for /f "delims=" %%b in ('type "%%a"') do (
  9.         set "line=%%b"
  10.         echo,!line:%source1%=%replaced1%!
  11.     ))>"%%~nxa.txt"
  12.     move /y "%%~nxa.txt" "%%~nxa"
  13.     popd
  14. )
复制代码





欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2