matching patterns and create new files

Viewed 64

I have a csv file named file1.csv:

something;AD;sss;Andorra;nothing;type_1;sss
something222;AD;sss222;Andorra;nothing222;type_2;aaa
thing;NL;thing3;Netherlands;thing;type_2;bb
etc;US;etc;United States;etc;type_2;nothing

I want to create separate files for each country. I make greps like that:

grep -e "\;AD\;.*\;Andorra\;" file1.csv > fileAD.csv
grep -e "\;NL\;.*\;Netherlands\;" file1.csv > fileNL.csv
grep -e "\;US\;.*\;United\sStates\;" file1.csv > fileUS.csv

This works, but I have all countries in the world. And i don't want to write these lines for every country. Is there any other solution ? Any help is really apreciated.

Edit: I updated my question. I also have a column with type_1 and type_2. And after all the files corresponding each country are created , I need to create new files for every country with just type_1 and new files with just type_2.

For example, for Andorra, I need the files:
fileAD.csv :

something;AD;sss;Andorra;nothing;type_1;sss
something222;AD;sss222;Andorra;nothing222;type_2;aaa

fileADtype_1.csv:

something;AD;sss;Andorra;nothing;type_1;sss

fileADtype_2.csv:

something222;AD;sss222;Andorra;nothing222;type_2;aaa

I think that is ok to look just for the column with the abbreviation, but i wanted the 2 columns, the one with "AD" and the one with the full_name "Andorra" for security reasons.

2 Answers

I go for a one liner with only one instance of awk, without temporary files:

awk -F ';' '{print >> "file" $2 ".csv"}' file1.csv

As one liner with awk:

for code in $(awk -F';' '{print $2}' data.csv | uniq); do awk -F';' -v pat="$code" '$2 ~ pat {print $0}' data.csv > "file${code}.csv"; done
Related