Badr Saadi
Badr Saadi

Reputation: 13

BATCH merge multiple file into one

i have a little problem, i have 3 txt file and i want to merge data into one csv with batch script

for exemple :

1.txt

Apple

Banana

Strawberry


2.txt

Red

Blue

Yellow


3.txt

One

Two

Three


What i want is a final.csv file with this sequence :

Apple;Red;One

Banana;Blue;Two

StrawberryYellow;Three

Can someone help me please ?


Thanks to everyone for answering me, I found another way that I will share with you in case someone needs it :

I used PowerShell to merge .csv files

here is the code : merge.ps1

#Import the CSVs
## GC = Get-Content
$csv1 = @(gc ".\1.csv")
$csv2 = @(gc ".\2.csv")
$csv3 = @(gc ".\3.csv")
# Create an Empty Array
$csv4 = @()
for ($i=0; $i -lt $csv1.Count; $i++) {
    $csv4 += $csv1[$i] + ';' + $csv2[$i] + ';' + $csv3[$i]
    }
# Output to file
$csv4 | Out-File ".\output.csv" -encoding default

# Delete the originals if you want
Remove-Item .\temp\1.csv
Remove-Item .\temp\2.csv
Remove-Item .\temp\3.csv

And in the batch script i have, i used this line to execute it : script.bat

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '.\merge.ps1'"

Upvotes: 1

Views: 876

Answers (1)

user6811411
user6811411

Reputation:

This batch will read 2 files in parallel, one with input redirection the other with a for loop. So to Merge 3 files it takes a two step approach. First merging 1.txt + 2.txt into a file 1+2.txt and at last merging this intermediate file with 3.txt into 1+2+3.txt. The filenames are passed to the batch via command line

:: Merge2Files.cmd File1 File2
@echo off&setlocal EnableDelayedExpansion
Set "Delim=;"
< "%~2" (
   for /F "usebackq delims=" %%a in ("%~1%") do (
      set File2Line=
      set /P File2Line=
      Echo:%%a%Delim%!File2Line!
   )
)

Output (stripped down)

C:\> Merge2Files.cmd 1.txt     2.txt >"1+2.csv"
C:\> Merge2Files.cmd "1+2.csv" 3.txt >"1+2+3.csv"
C:\> type 1+*.csv
1+2.csv
Apple;Red
Banana;Blue
Strawberry;Yellow

1+2+3.csv
Apple;Red;One
Banana;Blue;Two
Strawberry;Yellow;Three

Upvotes: 1

Related Questions