rcastellanosm rcastellanosm - 1 month ago 16
Bash Question

Bash Split CSV by Range

I have the following CSV File

"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


And i need to split the CSV in N new files based on the first character of the second Column in a BASH script

For example the script:

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


And the expected result must be:

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


And so on if i pass diferent fisrt letter in -from -to parameters

Thanks

Answer

You can accomplish something like this quite simply with awk.

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

Will return:

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

Not that this is case sensitive, so won't match columns like "Costa Rica","bird sanctuary",4321. To do this alter the command to:

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

Adapting this to a bash script should be simple enough, consider reading up a little on awk, getopts and regular expression matching.

Comments