1

I would like to split a large file based on elements in another file. Here is an example data for the first file:

Col1,Col2,Col3   
A,10,50  
B,10,05  
C,20,30  
B,20,03  
A,30,100  
C,30,111  
D,40,120  

The second file is:

A  
B  
C

I would like to save subset of file1 with first column takes value "A" to A.txt; and "B" to B.txt, and so on.

Before I am using

awk '$1=="A"' file1.txt > A.txt

but now I have to deal with 100+ different names in the second file, looking for a better way to get the job done. Thanks!!!

1 Answer 1

3

The basic elements of your case have been discussed many times on this site e.g.

Putting them together,

awk -F, 'NR==FNR {a[$1]++; next} $1 in a {print > $1 ".txt"}' file2.txt file1.txt
1
  • another option is using grep -Fwf second_file first_file | awk '{ print >$1".txt"}' ( assuming names in second_file only can appear in first column of first_file) Oct 28, 2018 at 15:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .