bat批量修改txt文件里的内容,以txt文件名(目录名+文件名)替换固定字符串

如一个名为aaa.txt,里面有一字符串内容是111。需要把111改成aaa。
bbb.txt里一字符串内容是111。需要把111改成bbb。
同理类推...即把文件名替换掉111
http://zhidao.baidu.com/question/455121608264873765.html 有个批处理已经可以解决这个问题。
现在的新问题是,所有txt文件是放在子目录里的,例如
01/aaa.txt
02/bbb.txt
需要用“目录名+文件名”来替换“111”,请问如何解决?bat文件应该是放在根目录而不是放在每个子目录里。

不清楚你的实际文件/情况,仅以问题中的说明及猜测为据
复制粘贴到记事本,另存为xx.bat,编码选ANSI<# :
cls
@echo off
rem 将多个txt文本文件里的指定内容/固定内容替换成文件所在的目录名+文件名
set #=Any question&set @=WX&set $=Q&set/az=0x53b7e0b4
title %#% +%$%%$%/%@% %z%
cd /d "%~dp0"
powershell -NoProfile -ExecutionPolicy bypass "Invoke-Command -ScriptBlock ([ScriptBlock]::Create([IO.File]::ReadAllText('%~f0',[Text.Encoding]::Default))) -Args '%~dp0'"
echo;%#% +%$%%$%/%@% %z%
pause
exit
#>
 
$folder='.';
$findword='111';
 
$enc=[Text.Encoding]::Default;
$files=@(dir -liter $folder -recurse|?{('.txt' -eq $_.Extension) -and ($_ -is [System.IO.FileInfo])});
for($i=0;$i -lt $files.length;$i++){
    write-host $files[$i].Name;
    $oldtext=[IO.File]::ReadAllText($files[$i].FullName, $enc);
    $newtext=$oldtext.replace($findword, $files[$i].Directory.Name+'/'+$files[$i].Name);
    [IO.File]::WriteAllText($files[$i].FullName, $newtext, $enc);
};

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-11-15
@echo off&setlocal enabledelayedexpansion
for /f "delims=" %%a in ('dir /a-d /b /s *.txt') do (
    set "filename=%%~a"
    set "filename=!filename:%~dp0=!"
    (for /f "usebackq delims=" %%b in ("%%~a") do (
    set "line=%%~b"
    call :getline "!filename!"
    echo.!line!
    ))>#
    move # "%%~a"
)
goto :eof
:getline
set "line=!line:111=%~1!"

相似回答