Spyros Agrafiotis
Spyros Agrafiotis

Reputation: 1

Split a CSV file using AWK, while reading from a different file for naming the output files

I have a CSV file as the following:

group1, item1
group1, item2
group2, item3
group1, item4
.....

I have managed to split this file by groups to separate csv files (group1.csv.dat, group2.csv.dat etc.). Each file contains all items belonging to a specific group.

group1.csv.dat:

item1, true
item2, true
item4, true
.....

group2.csv.dat:

item3, true
.....

I have used the following AWK:

awk -F, '{print $2",true" > $1".csv.dat"}' file1

Now, I have a second file (let's say file 2), as follows:

group1, GRFS+NC, 4
group2, GRTU+NC, 6 
....

How can I read this file using AWK in order to name the files created in the first step as GRFS4.csv.dat, GRTU6.csv.dat instead of group1.csv.dat, group2.csv.dat? Preferably, I would like to incorporate processing into the first step. Many thanks...

Upvotes: 0

Views: 98

Answers (2)

Ed Morton
Ed Morton

Reputation: 204701

You need something like this, untested:

awk '
NR==FNR{ name[$1] = $3 $6 ".csv.dat"; next }
{ print $2 ",true" > name[$1] }
' FS='[, +]' file2 FS=',' file1

Just count the fields in file2 to make sure $3 and $6 are the correct fields. Add a debugging for loop to print them all to see if you're not sure.

Upvotes: 0

Vijay
Vijay

Reputation: 67319

awk -F, '{split($2,a,"+");print $2",true" > a[1]""$3".csv.dat"}' file2

Upvotes: 1

Related Questions