简体   繁体   English

将多个 csv 文件与其中的文件名组合为 mac 终端上的行

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

I have multiple csv files.我有多个 csv 文件。 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.这可行,但我需要在合并之前将文件名添加到所有这些 csv 文件中,以便了解组合版本中的数据源。 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?有没有办法在mac终端上做到这一点?

You can create a shell script您可以创建 shell 脚本

#!/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:它将在combined.csv的.csv 文件中生成以下内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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