重命名子文件夹中的文件并通过批量覆盖

Rename files within subfolder and overwrite via batch

这是当前代码:

@ECHO OFF

ECHO.
REM rename 
REN "H:\DIRECTORY with Space\folder1\*.*" "H:\DIRECTORY with Space\Folder1\TEST_*.*"

ECHO.
DIR nofile || (PAUSE && EXIT /B 1)

我也试过 move / y

move /y "H:\DIRECTORY with Space\folder1\*.*" "H:\DIRECTORY with Space\folder1\TEST_*.*"

两者都不起作用(语法错误或找不到目录)。基本上尝试使用前缀 ("Test_") 重命名子文件夹中的所有内容并覆盖所有重复项。

Welp, seems Squashman has a better answer than me do.

Just to add something for his answer. (Sorry I can't comment.)

FOR /F "delims=" %%G IN ('DIR /a-d /b *.*') do ren "%%~G" "TEST_%%~G"

之后

添加这个可以帮助重命名目录中的 FOLDER(S)。 FOR /F "delims=" %%G IN ('DIR /ad /b *.*') do ren "%%~G" "TEST_%%~G"


但我建议使用:

for /f "delims=" %%a in ('DIR /a-d /s /b ^| findstr /v /c:"%~nx0") do (ren "%%a" "TEST_%%~nxa" >nul 2>nul )
for /f "delims=" %%a in ('DIR /ad /s /b ^| sort /r') do (ren "%%a" "TEST_%%~nxa" >nul 2>nul )

以及一些更扩展的功能:

@echo off
rem not necessary
title to whom it may rename
color 0a
mode 120,25
goto start
rem is necessary

:start
cls
echo Please enter the path which you want to rename all contents in it with a prefix. No need for the quotes.
echo %%cd%% for the current working directory
set /p p=The path: 
call set p=%p:"=%
echo.
if not exist "%p:"=%" (echo The folder doesn't exist in the typed in path.
echo Current working directory: "%cd%"
echo Please try another path. Press any key to continue.
pause >nul
goto start)
rem adding Squashman's answers here
pushd "%p%"
echo Renaming file(s) in the required folder.
for /f "delims=" %%a in ('DIR /a-d /s /b ^| findstr /v /c:"%~nx0") do (ren "%%a" "TEST_%%~nxa" >nul 2>nul )
echo Renaming (sub)folder(s) in the required folder.
for /f "delims=" %%a in ('DIR /ad /s /b ^| sort /r') do (ren "%%a" "TEST_%%~nxa" >nul 2>nul )
echo.
if "%cd%\" == "%~dp0" (echo Do you want to rename this batch too? It will auto exit after renaming.
choice /c yn /n /m "[Y/N] ")
if "%errorlevel%" == "1" (ren "%~nx0" "TEST_%~nx0" >nul 2>nul )
echo Renaming finished. Please press any key to leave the batch.
pause >nul
exit

试一试。我对代码进行了评论,以帮助更好地解释它是如何工作的。

@ECHO OFF

:: Changes to a directory and saves previous directory to go back to
PUSHD "H:\DIRECTORY with Space\folder1\"

:: Critical that you USE this instead of a normal FOR command.
:: A normal FOR command may attempt to rename a file twice.
FOR /F "delims=" %%G IN ('DIR /a-d /b *.*') do rename "%%~G" "TEST_%%~G"

:: Goes back to the previous directory.
POPD