Fedez
Fedez

Reputation: 61

Combining .csv and adding filename as column

Here is my concern. I have a folder with multiple .csv files in it, and I want to combine/merge them into one csv file but I need to add the filename of each csv as a column in the .csv itself so I can know which entry came from which csv file in the merged file. I have no experience in coding, however I found some solutions online that were supposed to do this.

The most succint one was this CMD line:

for /f %a in ('dir /b *.csv') do for /f "tokens=*" %b in (%a) do echo %b,%a >> all.csv

I basically navigate to my csv folder in CMD and then enter this line in and it executes, but there is no output, at all. So, I don't know what i'm doing wrong.

Oddly enough, when I execute it in another folder with csv files it works for another csv file. The only difference between that file and the other csv files is that the others (which it doesn't work for) were downloaded from the internet, and this one was created by me.

Can anyone help?

Update: Just checked, when I rename a file it works on it?

Upvotes: 6

Views: 8039

Answers (2)

ParashuRamu
ParashuRamu

Reputation: 26

You need to add the filename of each csv as a column in the .csv itself?

Before merging the files on that folder you need to create a comma separated row with your file name in each .csv file top row, according to no.of columns on that file.

Upvotes: 0

SharkDemon
SharkDemon

Reputation: 106

I tried to recreate your situation...as far as I can tell, your command works perfectly. Here's what I tried (on Windows):

  • I created a new folder.
  • I created 3 csv files in that folder ("file1.csv", "file2.csv", and "file3.csv")
  • I created a record (with 3 fields) in each of the 3 csv files, where a typical record might look like "100, 101, 102"
  • I opened the command prompt, navigated to the folder containing these csv files, and executed your command as-is.
  • The command processed the 3 csv files, and created a new file called "all.csv".
  • Each record in "all.csv" appears to be correct: the three data fields are present, and there is a fourth field present, which contains the name of the source csv file (e.g., "file1.csv").

You mention that it doesn't work when executing against files downloaded from the internet. Can you provide any further details about those files?

Upvotes: 6

Related Questions