1

I want to create a bat that takes the name of the directory where the file exists and the creation date of the file and adds it to the filename.

The image would be as follows
File name.txtFile name_Directory name_YYYYYMMDD.txt

Example file in University directory:

school_information.txt

Becomes:

school_information_university_20230909.txt  

This is the command that is currently being created.

@echo off
setlocal EnableDelayedExpansion

REM Get the current directory name
set "dirName=%CD%"
for %%a in ("%dirName%") do set "dirName=%%~nxa"

REM Rename the file
ren "file.txt" "file_!dirName!.txt"
Compo
  • 36,585
  • 5
  • 27
  • 39
david
  • 11
  • 1
  • Do you know that the creation date of a file is the date when the file was created in that directory? Copy a file from directory A to directory B and the last modification date is the same, but the creation date of the file in directory B is new and is now after the last modification date. – Mofi Aug 22 '23 at 06:11

1 Answers1

0

Try this:

  • process all .txt files in the directory
  • extract the creation date of each file
  • append both the folder name and the creation date to each file's name.
@echo off
setlocal EnableDelayedExpansion

set "dirName=%CD%"
for %%a in ("%dirName%") do set "dirName=%%~nxa"

for %%f in (*.txt) do (
    for /f "delims=" %%d in ('dir "%%f" /tc ^| find "%%f"') do (
        set "fullDate=%%d"
    )

    set "year=!fullDate:~6,4!"
    set "month=!fullDate:~0,2!"
    set "day=!fullDate:~3,2!"

    ren "%%f" "%%~nf_!dirName_!year!!month!!day!%%~xf"
)

endlocal
exit
Christian
  • 4,902
  • 4
  • 24
  • 42
  • 1
    I recommend removing the command `exit` from bottom of the batch file. It is unnecessary and counterproductive at end of a batch file. The inner `for` loop should have the single command `set "fullDate=%%d"` on same line as the `for` command without `(` and `)` as that is the syntax for which the command __FOR__ is designed for. I suggest reading also the __issue__ chapters in [this answer](https://stackoverflow.com/a/60686543/3074564). While the usage of the letters `a`, `d` and `f` as loop variables work here, it would be better using other letters like `g` and `h` or `i` and `j`. – Mofi Aug 22 '23 at 06:02
  • I suggest further reading [Rename multiple .csv file according to its file content](https://stackoverflow.com/a/76935408/3074564). I explained in this answer why it is not advisable to use a simple __FOR__ loop like `for %%f in (*.txt) do` when each found file is renamed in the directory with keeping the file extension `.txt`. The list of matched file names in file system changes in this case with each iteration of the loop making the result unpredictable, especially on drives with a FAT file system like FAT32 or exFAT. Better would be the usage of a `for /F` loop in this case. – Mofi Aug 22 '23 at 06:08