Home > Net >  Create a combined text file showing the date modified of each individual text file
Create a combined text file showing the date modified of each individual text file

Time:02-01

I have a few hundred text files in a folder. I want to combine all the files and form one file, archive1.txt:

  • I want to add the individual file names to each row of the new file
  • I want to add the 'Date Modified' value after the file name

The code fragment:

findstr "^" *.txt >> archive1.txt

adds only the name.

I found this:

forfiles /M *.txt /C "cmd /c echo @fdate @ftime"

which seems to find the 'Date Modified' for each file, but I can't seem to figure out how to combine the two and create one file with the both file name and modify date.

CodePudding user response:

The key to success is the ~t-modifier of for meta-variables:

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_ROOT=D:\Path\To\Root\Dir" & rem // (path to root dir.; use `%~dp0.` for batch file parent)
set "_MASK=*.txt"               & rem // (pattern of files to combine)
set "_FILE=archive1.txt"        & rem // (full name of the target file)

rem // Change into root directory:
pushd "%_ROOT%" && (
    rem // Write to target file:
    > "archive1.txt" (
        rem // Loop through all matching files except the target file:
        for /F "delims= eol=|" %%J in ('dir /B /A:-D-H-S "%_MASK%" ^| findstr /V /X /I /C:"%_FILE%"') do (
            rem // Store currently processed file:
            set "NAME=%%J"
            rem // Read current file with lines preceded by line numbers   `:` to maintain empty lines:
            for /F "delims=" %%I in ('findstr /N "^" "%%J"') do (
                rem // Store currently read line:
                set "LINE=%%I"
                rem // Toggle delayed expansion to avoid troubles with `!` and `^`:
                setlocal EnableDelayedExpansion
                rem // Remove line number prefix and write line with file name and date/time prefix:
                echo(!NAME!:%%~tJ:!LINE:*:=!
                endlocal
            )
        )
    )
    rem // Return from root directory:
    popd
)

endlocal
exit /B
  •  Tags:  
  • Related