Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split file based on string delimiter in bash.how? [duplicate]

Tags:

file

bash

split

I have this file.csv :

coordinate1,coordinate2,value1
11111,a1,65
11111,a2,32
22222,b1,39
22222,b3,55
33333,c5,12
33333,c9,16
coordinate1,coordinate2,value2
54656,a1,65
21342,a2,32
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
568568,c5,12
568568,c9,16
coordinate1,coordinate2,value3
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
11111,a1,65
11111,a2,32
22222,b1,39
22222,b3,55
33333,c5,12
33333,c9,16

Now I would like to split this file in 3 files , everyone whit only bloc of data

Es: 1° file
   coordinate1,coordinate2,value1
    11111,a1,65
    11111,a2,32
    22222,b1,39
    22222,b3,55
    33333,c5,12
    33333,c9,16

Es: 2° file
    coordinate1,coordinate2,value2
    54656,a1,65
    21342,a2,32
    23543,b1,39
    123123,b3,55
    568568,c5,12
    568568,c9,16
    123123,b3,55
    568568,c5,12
    568568,c9,16
like image 869
gairlo Avatar asked Dec 01 '09 12:12

gairlo


3 Answers

Blatantly stolen from this forum:

awk '/YOUR_TEXT_HERE/{n++}{print >"out" n ".txt" }' final.txt

should do the trick (replacing YOUR_TEXT_HERE, of course).

Replacing it with your conditions, and sending output to #file.txt with an input file of a.txt:

$ awk '/coordinate1,coordinate2,value?/{n++}{print > n "file.txt" }' a.txt
$ ls
1file.txt  2file.txt  3file.txt  a.txt
$ cat 1file.txt 
coordinate1,coordinate2,value1
11111,a1,65
11111,a2,32
22222,b1,39
22222,b3,55
33333,c5,12
33333,c9,16
$ cat 2file.txt 
coordinate1,coordinate2,value2
54656,a1,65
21342,a2,32
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
568568,c5,12
568568,c9,16
$ cat 3file.txt 
coordinate1,coordinate2,value3
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
23543,b1,39
123123,b3,55
568568,c5,12
568568,c9,16
123123,b3,55
11111,a1,65
11111,a2,32
22222,b1,39
22222,b3,55
33333,c5,12
33333,c9,16
like image 146
Mark Rushakoff Avatar answered Nov 17 '22 17:11

Mark Rushakoff


You could use csplit:

csplit file.txt /^c.*/ {*}

This syntax works on cygwin but haven't tried it elswhere.

like image 36
Spikolynn Avatar answered Nov 17 '22 18:11

Spikolynn


This differently quoted version of the other answer also works with Windows CMD:

awk "/coordinate1,coordinate2,value?/{n++}{print>n\"file.txt\"}" a.txt
like image 2
Armali Avatar answered Nov 17 '22 18:11

Armali