Batch Edit and Merge CSV Files

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
babsdoc
Posts: 2
Joined: 13 May 2013 12:34

Batch Edit and Merge CSV Files

#1 Post by babsdoc » 13 May 2013 12:48

Hi All,

This is my first post :)


I have 10 CSV files which I want to Merge which I have so far done by c:\type *.csv >> mergedfile.dat

***************FIRST PROBLEM*************************
The problem is I want to edit each csv file before it is merged so that the first/last column of the data (in each row) in it contains the filename. So if file XYZ.csv contains
1,2,3
2,3,4

Then I want the data to be,
XYZ,1,2,3
XYZ,2,3,4

***************SECOND PROBLEM*************************
When I use c:\type *.csv >> mergedfile.dat to merge the files I only want the headers from the first file in the batch and not the headers repeating as rows for the later files.

So if ABC.csv contains
H1,H2,H3
1,2,3

and XYZ.csv contains
H1,H2,H3
2,3,4

then mergedfile.dat should be
H1,H2,H3
1,2,3
2,3,4

and NOT
H1,H2,H3
1,2,3
H1,H2,H3
2,3,4

I hope that I have put across my questions clearly :)

Kindly help.

Respect,
babsdoc

Endoro
Posts: 244
Joined: 27 Mar 2013 01:29
Location: Bozen

Re: Batch Edit and Merge CSV Files

#2 Post by Endoro » 13 May 2013 14:25

try this

Code: Select all

@echo off&setlocal
(for %%a in (*.csv) do (
set /a filecount+=1
set /a linecount=0
set "file=%%~nxa"
for /f "delims=" %%i in ('^<"%%~a" findstr /n "^"') do (
set /a linecount+=1
set "line=%%i"
setlocal enabledelayedexpansion
set "line=!file!,!line:*:=!"
if !linecount! equ 1 (if !filecount! equ 1 (echo(!line!)) else (echo(!line!)
endlocal
)
))>"merge.dat"
type "merge.dat"

babsdoc
Posts: 2
Joined: 13 May 2013 12:34

Re: Batch Edit and Merge CSV Files

#3 Post by babsdoc » 13 May 2013 23:32

Endoro.... thanks a ton friend :)

Works like a charm !! Thanks once again, I'll be studying this piece of code :)

Regards,
babsdoc

Post Reply