简体   繁体   中英

Combine multiple csv files with filenames in it as rows on mac terminal

I have multiple csv files. I want to combine them in a single file and doing it like this on terminal;

"cat *.csv >combined.csv"

This works, but I need to add filenames to all of this csv files before merging in order to understand the source of data in the combined version. Now, I have this as combined;

a1, a2, a3, a4
b1, a2, a3, a4

I want to add filenames as rows to the beginning

file1, a1, a2, a3, a4
file2, b1, a2, a3, a4

Is there any way to do that on mac terminal?

You can create a shell script

#!/bin/sh

rm combined.csv
for f in *.csv
do
  sed -e "s/^/${f},/" $f >> combined.csv
done

It will produce the following in the combined.csv file:

file1.csv,a1, a2, a3, a4
file2.csv,b1, a2, a3, a4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM