Windows batch merge multiple text files

Viewed 32

I've been looking for a solution to my problem, but couldn't find an answer. I'm desperate.

I need to create a script, which concatenates multiple text files into one. my files in folder like this

- aaaa.txt
- aaaa (1).txt
- aaaa (2).txt
- aaaa (3).txt
- bbb.txt
- bbb (1).txt
- bbb (2).txt
- bbb (3).txt

i want merge file like this

- aaaa.txt
- bbb.txt

i have tried like this

@echo off
for /r "." %%a in (*.txt) do (
   echo %%~na
   type %%a >> %%~na.txt
)

but merge file is empty

1 Answers
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following setting for the source directory is a name
rem that I use for testing and deliberately includes spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files\t w o"

FOR %%b IN ("%sourcedir%\*(*).txt") DO (
 for /f "delims=(" %%e in ("%%~nb") do (
  set "destfilename=%%e"
  if "!destfilename:~-1!"==" " (
   type "%%b">>"%sourcedir%\!destfilename:~0,-1!.txt"
  ) else (
   type "%%b">>"%sourcedir%\%%e.txt"
  )
  ECHO del "%%b"
 )
)

GOTO :EOF

Always verify against a test directory before applying to real data.

Process a list of filenames matching the *(*.txt mask.

Derive the base name by re-processing the name part, tokenising on (.

Append the file found to the basename.txt; If the last character of the base name is Space, then remove that terminal space so the destination will not be "basenameSpace.txt".

The del is merely echoed, to be enabled by removing the echo if desired after testing.

Note this does not perform recursion as implied by the original code, and also processes files named basename(?).txt as well as basename(?) .txt- and the basename may not contain (

Related