bash 如何根据列值将 CSV 文件拆分为多个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30900331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:13:20  来源:igfitidea点击:

How to split a CSV file into multiple files based on column value

bashcsvawk

提问by user3616643

I have CSV file which could look like this:

我有一个 CSV 文件,它看起来像这样:

name1;1;11880
name2;1;260.483
name3;1;3355.82
name4;1;4179.48
name1;2;10740.4
name2;2;1868.69
name3;2;341.375
name4;2;4783.9

there could more or less rows and I need to split it into multiple .dat files each containing rows with the same value of the second column of this file. (Then I will make bar chart for each .dat file) For this case it should be two files:

可能会有更多或更少的行,我需要将其拆分为多个 .dat 文件,每个文件都包含与该文件第二列具有相同值的行。(然后我将为每个 .dat 文件制作条形图)对于这种情况,它应该是两个文件:

data1.dat 
name1;1;11880
name2;1;260.483
name3;1;3355.82
name4;1;4179.48

data2.dat
name1;2;10740.4
name2;2;1868.69
name3;2;341.375
name4;2;4783.9

Is there any simple way of doing it with bash?

有没有什么简单的方法可以用 bash 做到这一点?

回答by Andrzej Pronobis

You can use awk to generate a file containing only a particular value of the second column:

您可以使用 awk 生成仅包含第二列特定值的文件:

awk -F ';' '(==1){print}' data.dat > data1.dat

Just change the value in the $2==condition.

只需更改$2==条件中的值。

Or, if you want to do this automatically, just use:

或者,如果您想自动执行此操作,只需使用:

awk -F ';' '{print > ("data"".dat")}' data.dat

which will output to files containing the value of the second column in the name.

这将输出到包含名称中第二列值的文件。

回答by Cyrus

Try this:

尝试这个:

while IFS=";" read -r a b c; do echo "$a;$b;$c" >> data${b}.dat; done <file