vkaul11
vkaul11

Reputation: 4214

how to create files that retain column names with specific values

I have a file where first column takes certain values (in this case 4)

product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
negative,0 0 1, sight
city,0 0 2,grind

I want to construct 3 files one with 3 column values, one with 2 column values and one with 1 column value. *In addition one of those values has to be "product"

file3.txt

product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar
negative,0 0 1, sight

file2.txt

product,0 0,no way
brand,0 0 0,detergent
product,0 0 1,sugar

file1.txt

product,0 0,no way
product,0 0 1,sugar

Can this procedure be automated in awk? At this point I am manually making the file with column names to retain and using this

awk 'NR==FNR{v[$1]; next} $1 in v' values.txt FS=, datafile

Upvotes: 1

Views: 132

Answers (2)

Diego Torres Milano
Diego Torres Milano

Reputation: 69218

You can try

#! /usr/bin/awk -f

BEGIN { FS=","}
{ 
    if (length(w) < m && !($1 in w)) w[$1]=1
    if ($1 in w) print
}

chmod it and invoke it like

$ ./script.awk -v m=3 datafile > file3.txt

where m is the number of unique values

EDIT

Loop

for m in $(seq 100); do ./script.awk -v m=$m datafile > file$m.txt; done

Upvotes: 1

miken32
miken32

Reputation: 42715

This lacks a certain elegance, but it works.

awk -F, '{
if(!one) one=$1;
if(!two && $1 != one) two=$1;
if(!three && $1 != one && $1 != two) three=$1;

if (one && $1==one) {print $0 > "file1.txt"; print $0 > "file2.txt"; print $0 > "file3.txt";}
if (two && $1==two) {print $0 > "file2.txt"; print $0 > "file3.txt";}
if (three && $1==three) print $0 > "file3.txt";
}' values.txt

Upvotes: 0

Related Questions