I have the following text files:


water melon10.txt
water melon11.txt
water melon12.txt

I'd like to merge all apples into one txt file - apple_all.txt and all water melons into another - water melon_all.txt

Note that the space in water melon is on purpose - some txt file names have spaces in them.

All files are in one folder. The order of merging is irrelevant.



@echo off
>"%~1_all.txt" (
  for %%F in ("%~1*.txt") do if /i "%%F" neq "%~1_all.txt" type "%%F"


merge apple
merge "water melon"

Or, putting everything in one batch script:

@echo off
call :merge apple
call :merge "water melon"
exit /b

>"%~1_all.txt" (
  for %%F in ("%~1*.txt") do if /i "%%F" neq "%~1_all.txt" type "%%F"
exit /b

Programmatically figuring out all the fruit in the folder is not trivial, since there is no easy way in batch to trim all of the trailing digits from the base name of a file. Here is once solution (untested):

@echo off
setlocal disableDelayedExpansion
del *_all.txt 2>nul
for /f "delims=" %%F in (
  'dir /b /a-d *.txt^|findstr "[^0-9][0-9]*\.txt$"'
) do call :proc "%%F"
exit /b

set "file=%~1"
set "fruit=%~n1"
setlocal enableDelayedExpansion
if "!fruit:~-1!" geq "0" if !fruit:~-1!" leq "9" (
  set "fruit=!fruit:~0,-1!"
  goto :trimNum
type "!file!" >>"!fruit!_all.txt"
exit /b
  • Can the script deduct the name of the file on its own - as there are many "fruits" so putting them all inside the batch script like call :merge apple call :merge "water melon" would be very tedious? – kat May 6 '14 at 12:51
  • @kat - see updated answer – dbenham May 6 '14 at 16:41
  • @kat don't forget to mark this as answer – Jet May 6 '14 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.