1

I'm trying to merge txt files in a dir using the following

@echo off
cd /d C:\textfiles\
for %f in (*.txt) do type "%f" >> C:\Users\Desktop\output.txt

But I am not getting any output (because last line I'm pretty sure) , can anyone help me out here?

Also how can I make the output filename automatically append text or date for the date e.g. output_random.txt or output_19.06.14.txt ?

Edited code (thanks to Stephan) but not appending date:

@echo off
cd /d "C:\TextFiles"
for /f %%i in ('wmic os get localdatetime ^|find "20"') do set dt=%%i
set dt=%dt:~0,8%
for %%f in (*.txt) do type "%%f" >> C:\TextFiles\output-%dt%.txt
  • Also `copy c:\textfiles\*.txt C:\Users\Desktop\output.txt` is probably more straightforward. See `copy /?`. – phd443322 Jun 19 '14 at 07:09
  • Hi mate, thanks this seems a lot more straightforward although I wonder what the differences are? none? – comingbacksoonbyefornow Jun 19 '14 at 08:45
  • You you were just doing it the hard way. Of course copy isn't flexible while for loops are. Also `forfiles` (`forfiles/?`) is meant to replace `for` lops for simple things like this (and other common uses of `for`). FOR loops are ugly. – phd443322 Jun 19 '14 at 09:44

1 Answers1

4

Inside batchfiles, you have to use %%f instead of %f, which works on commandline only:

for %%f in (*.txt) do type "%%f" >> C:\Users\Desktop\output.txt

for the "Random or Date" part:

As you say "random or date", I assume, the date don't have to have a specific format. Best way (because independent of locale settings) would be:

for /f %%i in ('wmic os get localdatetime ^|find "20"') do set dt=%%i
set dt=%dt:~0,8%

%dt% will be in the format YYYYMMDD. You can easily add the time with set dt=%dt:~0,14% (YYYYMMDDhhmmss) and output to ...output-%dt%.txt

for formatting %dt% to DD-MM-YYYY:

set dt=%dt:~6,2%-%dt:~4,2%-%dt:~0,4%

Extended Reading - How does the Windows Command Interpreter (CMD.EXE) parse scripts?

Community
  • 1
  • 1
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Hi Stephan, thanks a lot, the merge function is working now! One problem though is the date is not appending to the output file. I have edited my top post to show my current code. Can you also tell me how I can get the date format into DD-MM-YYYY? – comingbacksoonbyefornow Jun 19 '14 at 08:38
  • What do you mean with "not appending to the outputfile"? "Appending to the filename" or "writing it into the file contents"? For formatting the date, see my edit. – Stephan Jun 19 '14 at 09:15
  • Not appending as in I set output file as C:\TextFiles\output-%dt%.txt but the actual file that is outputted is "output.txt" – comingbacksoonbyefornow Jun 19 '14 at 09:24
  • Hey, I just tried your DD-MM-YYYY formatting for date and now it works! I think the previous date formatting (dt) may have been not correct? either way it now works and thank you very much, Stephan! :) – comingbacksoonbyefornow Jun 19 '14 at 09:26