0

I'm a novice to windows batch - I want to concatenate multiple text files into one using windows batch. The files to be combined are specified in a list and could be dynamic. I have a single directory of files a.txt, b.txt, c.txt .... z.txt. I need to concatenate a subset of them into a merged.txt For example if list is the input list

set list=a f z

Then I want the merged.txt to have contents of a.text, f.txt and z.txt. Ideas I have already tried are

1)type *.txt > merged.txt :- wont work for me as that would combine all text files.

2)copy a.txt+f.txt+z.txt merged.txt :-But that would only combine just for this one input.

Does anyone have any ideas ?

Praneeth
  • 178
  • 4
  • 16
  • 2
    That's not an array, that's a list (you even named it `list`). `for %%a in (%list%) do type %%a.txt >>merged.txt` – Stephan Jun 21 '19 at 19:38
  • @Stephan thanks for pointing it out. Let me change it to list. Your solution does work for me. I had to change %%a to %a though (refer https://stackoverflow.com/questions/9311562/a-was-unexpected-at-this-time ) Thanks a ton ! – Praneeth Jun 21 '19 at 19:50
  • 2
    yes - it's `%a` on command line, but `%%a` in batch files. – Stephan Jun 21 '19 at 19:53

2 Answers2

1

Not sure how you want to call your batch file, so that is up in the air.

But I think you were close with the copy a.txt+f.txt+z.txt merged.txt

Just build that list dynamically using command line arguments (you can have up to 9)

@echo off
set copyfiles=

for /d %%i in (%*) do call :process %%i
goto :output

:process
if "%copyfiles%" NEQ "" (
  set copyfiles=%copyfiles%+%1.txt
)
if "%copyfiles%" EQU "" (
  set copyfiles=%1.txt
)
goto :end

:output
copy %copyfiles% merge.txt

:end

This would then be executed with

merge-them.cmd a b c f

Or you could set a variable like

mylist=a,b,c,f

Then your FOR loop would reference %mylist% instead of %*

Mike C
  • 121
  • 7
  • I tried your solution. Pretty nice that you can dynamically input the files to be merged. But in my case I read the list of files to be merged from another file, so Stephan's solution is enough for me. – Praneeth Jun 24 '19 at 15:12
1

The for command is intended to process lists:

set "list=a f z"
for %%a in (%list%) do type %%a.txt >>merged.txt

Note: %%a is batch file syntax. If you want to use it directly on command line, use %a instead.

The following is faster (because it opens the destination file just one time), but you won't notice it with only a few entries in the list (with a huge list this can be several hundred times faster):

(for %%a in (%list%) do type %%a.txt)>merged.txt
Stephan
  • 53,940
  • 10
  • 58
  • 91