按范围按Bash拆分CSV

时间:2016-10-11 12:46:08

标签: bash shell csv sh

我有以下CSV文件

"Costa Rica","Aberdeen Research",10152
"Costa Rica","Applebees Lab",14562
"Costa Rica","Bride Research",10452
"Costa Rica","Complex Teams",4512
"Costa Rica","Dynamic Air",7854
"Costa Rica","Electronict Arts",7851

我需要根据 BASH 脚本中第二列的第一个字符将N个新文件中的CSV拆分

例如脚本:

$: ./split.sh -from A -to C file.csv

预期结果必须是:

"Costa Rica","Aberdeen Research",10152
"Costa Rica","Applebees Lab",14562
"Costa Rica","Bride Research",10452
"Costa Rica","Complex Teams",4512

依旧如果我在-from -to参数中传递不同的fisrt字母

由于

1 个答案:

答案 0 :(得分:2)

你可以用awk完成这样的事情。

awk -F "," '$2 ~ /^\"[A-C]/' < file.csv

将返回:

"Costa Rica","Aberdeen Research",10152
"Costa Rica","Applebees Lab",14562
"Costa Rica","Bride Research",10452
"Costa Rica","Complex Teams",4512

请注意,这是区分大小写的,因此不会与"Costa Rica","bird sanctuary",4321之类的列匹配。要执行此操作,请将命令更改为:

awk -F "," '$2 ~ /^\"[a-cA-C]/' < file.csv

将其改编为bash脚本应该很简单,考虑在awk,getopts和正则表达式匹配上阅读一些内容。