Reputation: 2559
Good day,
I was wondering how to split a matrix into files if pattern at specific column match.
Pattern: when find zero at second column, split.
So far I have done:
cat file | awk -FS"\t" '$2==0 {close("result"f);f++}{print $0 > "result"f}'
Input
1 2
2 3
4 0
5 6
7 0
Expected output
File 1
1 2
2 3
4 0
File 2
5 6
7 0
Thank in advance for any clue
Upvotes: 2
Views: 163
Reputation: 113844
awk -v n=1 '{print>("file-" n)} $2==0 {n++}' input
Explanation:
From your input data, there appears to be no need to set the field separator to a tab. By default, awk
splits fields on any whitespace, tabs included.
-v n=1
The name of the output file is determined by the variable n
. We start it at 1
.
{print>("file-" n)}
This prints the current line to a file whose name depends on n
.
$2==0 {n++}
If the second column is zero, we increment n
so that the next line goes to a new file.
Upvotes: 1
Reputation: 80931
-FS"\t"
isn't doing what you think it is. awk sees that as -F 's\t'
that is you are setting FS
to s<tab>
.
You want -F"\t"
or -v FS="\t"
.
You also need to print out the current line before you close the old file.
Upvotes: 1