在一系列批处理文件中搜索并用大写字母替换字符串

Search and replace string with uppercase letters in series of batch-files

您好,我正在尝试在一系列文件夹中的一系列批处理文件中搜索并替换包含用户名的字符串。 IE。我在网络驱动器上有一系列批处理文件,需要将它们传输到一些同事的本地 pc 驱动器,在此过程中我需要更改批处理文件中的用户名以匹配本地 PC 的用户名。并且用户名必须全部大写。为此,我使用了一段代码,我曾经对单个文件执行相同的操作,但是我在转换代码以对一系列文件夹中的一系列文件执行相同操作时遇到了问题。我正在 windows 7 机器上工作。我试过的代码如下(请注意,第一段代码将网络驱动器(O:-drive)的树结构镜像到本地驱动器(B:-drive)并复制不需要的文件在移动过程中改变。给我带来麻烦的部分是从SETLOCAL ENABLEDELAYEDEXPANSION):

这行开始的
for /f "delims=" %%a in ('dir /b/ad "o:\afstem*" ') do (

echo m | xcopy /t /e /y "o:\%%a\Ta" "b:\%%a\Ta"

mkdir "b:\%%a\Nyta"

echo f | xcopy /s /y /d "o:\%%a\Ta\*moms" "b:\%%a\Ta\*moms"

SETLOCAL ENABLEDELAYEDEXPANSION
SET String=%username%

CALL :UpCase String

set txtfile=o:\%%a\Ta\*.bat
set newfile=b:\%%a\Ta\*.bat
if exist "%newfile%" del /f /q "%newfile%"
set search=SHL
set replace=%String%
for /f "tokens=*" %%a in (%txtfile%) do (
    set newline=%%a
    call set newline=%%newline:%search%=%replace%%%
    call echo %%newline%% >>%newfile%
)

ENDLOCAL
GOTO:EOF)


:UpCase
:: Subroutine to convert a variable VALUE to all upper case.
:: The argument for this subroutine is the variable NAME.
SET %~1=!%1:a=A!
SET %~1=!%1:b=B!
SET %~1=!%1:c=C!
SET %~1=!%1:d=D!
SET %~1=!%1:e=E!
SET %~1=!%1:f=F!
SET %~1=!%1:g=G!
SET %~1=!%1:h=H!
SET %~1=!%1:i=I!
SET %~1=!%1:j=J!
SET %~1=!%1:k=K!
SET %~1=!%1:l=L!
SET %~1=!%1:m=M!
SET %~1=!%1:n=N!
SET %~1=!%1:o=O!
SET %~1=!%1:p=P!
SET %~1=!%1:q=Q!
SET %~1=!%1:r=R!
SET %~1=!%1:s=S!
SET %~1=!%1:t=T!
SET %~1=!%1:u=U!
SET %~1=!%1:v=V!
SET %~1=!%1:w=W!
SET %~1=!%1:x=X!
SET %~1=!%1:y=Y!
SET %~1=!%1:z=Z!
GOTO:EOF

提前感谢您的任何 help/suggestions

更新

感谢 Dmitry Sokolow 提供的以下代码解决了我的问题

set txtfile=o:\%%a\Ta\*.bat
set newfileprefix=b:\%%a\Ta\
set search=SHL
set replace=!String!
for %%F in (!txtfile!) do (
    if exist "!newfileprefix!%%~nxF" del /f /q "!newfileprefix!%%~nxF"   
    for /f "tokens=*" %%Z in (%%F) do (
        set newline=%%Z
        call set newline=%%newline:!search!=!replace!%%
        echo !newline! >>!newfileprefix!~nx%%F
    )
)

for循环中你应该使用!var!得到var的实际值,所以

set txtfile=o:\%%a\Ta\*.bat
set newfile=b:\%%a\Ta\*.bat
if exist "!newfile!" del /f /q "!newfile!"
set search=SHL
set replace=!String!
for /f "tokens=*" %%Z in (!txtfile!) do (
    set newline=%%Z
    call set newline=%%newline:!search!=!replace!%%
    echo !newline! >>!newfile!
)

更新。

set txtfile=o:\%%a\Ta\*.bat
set newfileprefix=b:\%%a\Ta\
...
for %%F in (!txtfile!) do (
    for /f "tokens=*" %%Z in (%%F) do (
        set newline=%%Z
        call set newline=%%newline:!search!=!replace!%%
        echo !newline! >>!newfileprefix!%%F
    )
)