0

I have the following text files:

apple1.txt
apple2.txt
apple3.txt

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.

1 Answer 1

3

MERGE.BAT

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

Usage:

merge apple
merge "water melon"

Or, putting everything in one batch script:

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

:merge
>"%~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

:proc
set "file=%~1"
set "fruit=%~n1"
setlocal enableDelayedExpansion
:trimNum
if "!fruit:~-1!" geq "0" if !fruit:~-1!" leq "9" (
  set "fruit=!fruit:~0,-1!"
  goto :trimNum
)
type "!file!" >>"!fruit!_all.txt"
exit /b
3
  • 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, 2014 at 12:51
  • @kat - see updated answer
    – dbenham
    May 6, 2014 at 16:41
  • @kat don't forget to mark this as answer
    – Jet
    May 6, 2014 at 16:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .