Text Processing – Save Each Line from CSV to New File with Filename from Column

csvtext processing

I have a csv file on a Linux machine like this:

value1 value2 name  
1      2      a  
2      3      b  
4      5      c  

What I want is to split the n entries in this csv into n text files with just the corresponding numbers in that file separated by space. N is determined by the value in name.

So above csv would become:

  • a.txt containing 1 2
  • b.txt containing 2 3
  • c.txt containing 4 5

In case there are multiple entries for a particular name then those should go together to one file.

Ex if there was

1  2  a   
21 31 a

then there should be a single a.txt with

1  2     
21 31

Best Answer

It's pretty simple actually

awk '{print $1, $2 > $3 ".txt"}' file.csv

You should only run into to trouble if there will be more than about one thousand new files

Related Question