Extract data with awk and write to several files

Hi!

I have one file with data that looks like this:

1 data data data data
2 data data data data
3 data data data data
.
.
.
1 data data data data
2 data data data data
3 data data data data
.
.
.

I would like to have awk to write each block to a separate file, like this:

1 data data data data
2 data data data data
3 data data data data
.
.
.

To filename.1, the other block to filename.2 etc

How many blocks there are will not be constant.

So awk will write to one file until $1 is equal to 1, and then write to another file until $1 is equal to 1 again etc.

I was thinking about using while, but I can't wrap my head around it..
Is there someone who could enlighten me ?

Thanks.

Martin.

Try:

awk 'BEGIN{x=0}$1==1{x+=1}{print $0 >"filename."x;}' file
1 Like
awk '$1==1{x++}{print >> ("filename"x)}' file
1 Like

Thanks guys !
Your one-liners is doing what I wanted.

Awk really is a powerful tool :slight_smile:

Martin.