Recursively append folder name to the files in Windows batch file

我是研究僧i 提交于 2019-12-08 10:44:41

问题


I would like to append my folder name to all the available .txt files inside a subfolder. Below is the file/directory structure. I need to achieve this in Windows BATCH script.

C:\Source\Source1\1\a.txt C:\Source\Source1\1\b.txt

C:\Source\Source1\2\a.txt C:\Source\Source1\2\b.txt

C:\Source\Source2\3\a.txt C:\Source\Source2\3\b.txt

The above files should be renamed like below:

C:\Source\Source1\1\1_a.txt C:\Source\Source1\1\1_b.txt

C:\Source\Source1\2\2_a.txt C:\Source\Source1\2\2_b.txt

C:\Source\Source2\3\3_a.txt C:\Source\Source2\3\3_b.txt

Similary, I have Source1...Source30 and under each source directory, I will have multiple folders with different numbers. I need to rename all the files under these directories and append the number(directory name) to the file name.

So far below is what I wrote:

for %%* in (.) do set CurrDirName=%%~nx*
echo %CurrDirName%

for /r %%x in (*.txt) do ren "%%x" "%CurrDirName%_%%x"

With this, I am able to achieve it in a single directory. I couldn't make it recursive. Could you guys please help me with this.


回答1:


@echo OFF
SETLOCAL EnableExtensions
for /F "delims=" %%G in ('dir /B /S "C:\Source\*.txt"') do (
    for %%g in ("%%~dpG.") do ECHO rename "%%~fG" "%%~nxg_%%~nxG"
)
pause

where the FOR loops are:

  • outer %%G loop creates a static list of .txt files (recursively), and
  • inner %%g loop gets the parent folder of every particular file.

The rename command is merely displayed using ECHO for debugging purposes. To make it operational, remove word ECHO (no sooner than debugged).

Moreover, I'd consider checking whether a particular file is already renamed…



来源:https://stackoverflow.com/questions/42565519/recursively-append-folder-name-to-the-files-in-windows-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!