USLG
USLG

Reputation: 25

How do I add the folder name to the file being created in my batch file?

I'm using -

for /d /r %%a in (*) do (
    del "%%~fa\COMBINED_NAD.TXT" >nul 2>nul 
    copy /b "%%~fa\*NAD.TXT" "%%~fa\COMBINED_NAD.TMP"
    ren "%%~fa\COMBINED_NAD.TMP" "COMBINED_NAD.TXT"
)

Which works great, but I also need it to include the directory folder name in the file it is creating - for example I want the output to be something like - "%DIR%_COMBINED_NAD.TXT".

Does anyone know what I need to add? Thanks for the help.

Upvotes: 1

Views: 34

Answers (1)

Pokechu22
Pokechu22

Reputation: 5046

Depending on the output you want, there's several possible solutions.


  1. Excludes base directory.

If the program was run in C:\Users\Example\Documents\, and was in the folder C:\Users\Example\Documents\Example\Something\, the result would be Example_Something_COMBINED_NAD.TXT.

setlocal enabledelayedexpansion

for /d /r %%a in (*) do (
    del "%%~fa\COMBINED_NAD.TXT" >nul 2>nul 
    copy /b "%%~fa\*NAD.TXT" "%%~fa\COMBINED_NAD.TMP"
    set dir=%%~fa
    set dir=!dir:%cd%\=!
    set dir=!dir:\=_!
    ren "%%~fa\COMBINED_NAD.TMP" "!dir!_COMBINED_NAD.TXT"
)

The important bit here is this:

set dir=%%~fa
set dir=!dir:%cd%\=!
set dir=!dir:\=_!

The first line sets dir to %%~fa, which is the folder currently being processed.
The second line replaces all occurences of the value of %cd% (the directory in which the program was started) to (blank) inside of dir.
The third line replaces all slashes with underscores. (File names can't have slashes in them)

Note that this uses !varname! rather than %varname%. This is explained in the help for set, and is why setlocal enabledelayedexpansion is needed.


  1. Includes base directory.

If the program was run in C:\Users\Example\Documents\, and was in the folder C:\Users\Example\Documents\Example\Something\, the result would be Users_Example_Documents_Example_Something_COMBINED_NAD.TXT.

setlocal enabledelayedexpansion

for /d /r %%a in (*) do (
    del "%%~fa\COMBINED_NAD.TXT" >nul 2>nul 
    copy /b "%%~fa\*NAD.TXT" "%%~fa\COMBINED_NAD.TMP"
    set dir=%%~pa
    set dir=!dir:\=_!
    set dir=!dir:~1!
    ren "%%~fa\COMBINED_NAD.TMP" "!dir!_COMBINED_NAD.TXT"
)

The important bit here is this:

set dir=%%~pa
set dir=!dir:\=_!
set dir=!dir:~1!

It's very similar to the first one, but a few changes have been made.

The first line sets dir to the folder but not the drive letter.
The second line replaces slashes with underscores (same reason as above).
The third line sets dir to 1 char into dir. This is needed as otherwise it would output with a leading underscore.


I do not know of a solution that produces Something_COMBINED_NAD.TXT if the program was run in C:\Users\Example\Documents\, and was in the folder C:\Users\Example\Documents\Example\Something\.

Upvotes: 1

Related Questions