Monday, March 17, 2008

Send alternate lines to separate files - AWK


I already explained about subdividing a file in my previous post http://unstableme.blogspot.com/2008/01/subdividing-file-bash-newbie.html

Here are some more and useful one.

$ cat file1
one
two
three
four
five
six
seven

Purpose1:

Send alternate lines to 2 different files. i.e. 1st,3rd,5th,7th line should go to newfile1 and 2nd,4th,6th line should go to newfile2. i.e odd lines to newfile1 and even lines to newfile2


$ awk 'NR%2 {print > "newfile1"}' file1

or

$ sed -n 'p;n' file1 > newfile1


$ cat newfile1
one
three
five
seven

$ awk '(NR+1)%2 {print > "newfile2"}' file1

or

$ sed -n 'n;p' file1 > newfile2


$ cat newfile2
two
four
six

Purpose2:

Send every consecutive 3 lines into separate files myfile_1,myfile_2..

$ awk '{print >("myfile_" int((NR+2)/3))}' file1

$ cat myfile_1
one
two
three

$ cat myfile_2
four
five
six

$ cat myfile_3
seven

Purpose3:

Send every consecutive 2 lines into separate files myfile_1,myfile_2..

$ awk '{print >("myfile_" int((NR+1)/2))}' file1

8 comments:

Kristian said...

Thanks, that's helpful! What if I only wanted every 4 lines of a file? (And I didn't want to run this twice.)

Unknown said...

@Kristian, do you mean every 4 lines to a sub file ?

If yes,

awk '{print >("myfile_" int((NR+3)/4))}' file.txt

Unknown said...

Hey man,
How it's possible to send the lines to two files based on a parameter in one column?
e.g. If the parameter in the 4th column was 0 send to file1, otherwise, send to file2.

tnx

Unknown said...

@Aman Zare: Thanks for the query.

I think this will help you

http://unstableme.blogspot.in/2009/09/split-file-using-awk-few-examples.html

Please let me know if you find any difficulty here. Thanks.

Unknown said...

Thanks for your reply!
It doesn't work for me...
when I try to apply it for 4th column it prints exactly the same input as output. When I apply it for first column it gives as many as the lines in input file, without no categorization.

My input file is like this:
1 1 0
44 1 0
56 1 0
126 1 0
154 1 8
199 3 8
200 1 8

I like to make two files regarding the 3rd column's difference. one for those with "0" and one for "8".

Thanks again! :)

Unknown said...

It worked! My mistake! instead of using
awk -F "," '{close(f);f=$1}{print > f".txt"}' inputfile
I should have used
awk '{close(f);f=$1}{print > f".txt"}' inputfile
cause I have a tab delimited file.

Thanks again man! ;)

Unknown said...

@Aman Zare, great. Thanks.

SID said...

Thanks much Dude. It saved my time.

© Jadu Saikia www.UNIXCL.com