Merge/concatenate all text files in a folder/directory older than 1 day into one text file in batch file (run.bat)
I would like to merge text files that are older than 1 day into output.txt file in bat/cmd.
if I am running "run.bat" on 28th October 2021 for currently available files in folder where it should merge only 27th October 2021 dates files. so with below files in folder the "run.bat" should merge first three files
File Name |
---|
XXXXX_27Oct2021-050034.txt |
YYYYY_27Oct2021-045233.txt |
YYYYZ_27Oct2021-045233.txt |
XXXXX_28Oct2021-050034.txt |
YYYYY_28Oct2021-045233.txt |
YYYYZ_28Oct2021-045233.txt |
presently I managed to merge with below cmd but it does merge all the text files into output.txt in folder.
type *.txt > newfile.txt
is there any way we can specify part of file name to search like this and merge
set getDate = format(currentdate - 1,"ddMMMyyyy")
type %getDate% *.txt > newfile.txt
apologies for wrong syntax or my thought process.
Thank you!!!
Solution 1:
A little call out to Powershell within a batch file to get yesterday's date into a variable.
for /F "usebackq delims=" %%G IN (`powershell -command "(Get-Date).AddDays(-1).ToString('ddMMMyyyy')"`) do set "ydate=%%G"
Then you can use wildcards with the copy command to combine the files together.
copy "*_%ydate%-*.txt" "newfile.txt"
So this will only copy files with yesterdays date. If you want all files older than 1 day then you would use the FORFILES
solution.
Solution 2:
Using type and an output file is indeed an easy way to merge several txt files. You can combine the type command with the ForFiles command in order to only type the files that are older than one day. This would look something like this:
ForFiles /p "C:\someFolder" /m *.txt /d -1 /c "cmd /c type @file" > output.txt