Split the single file lines into multiple files

Let's assume that I have a file name called �A' and it has 100 lines in it and would like to split these 100 lines into 4 files as specified bellow.

INPUT: Input file name A
1
2
3
4
5
6
7
8
9
........100

Output: 4 output files (x,y,z,w)

File x should contains (Skip 4 lines)
1
5
9
13
17
21
............

File y should contains (skip 4 lines)
2
6
10
14
18
22
...........

File z should contains (skip 4 lines)
3
7
11
15
19
23
...................

File w should contain (skip 4 lines)
4
8
12
16
20
24

Regards
Subba

What have you tried?

sed -n '1,${p;n;n;n;}' A > x
sed -n '2,${p;n;n;n;}' A > y
sed -n '3,${p;n;n;n;}' A > z
sed -n '4,${p;n;n;n;}' A > w
sed -n 'w x
     n; w y
     n; w z
     n; w w' A

Hi
Awk answer for this one will be ;

awk 'BEGIN{a[1]="x";a[2]="y";a[3]="z";a[0]="w";} {var=NR%4;file=a[var];print > file;}' A

Thanks
Guru.

awk '{print >>("file"(NR%4))}' file

try

sed -n -e '1~4w x' -e '2~4w y' -e '3~4w z' -e '4~4w a' Your_file_name

Contrary to your nick, that tilde address step syntax is a GNU extension :wink:
(I mention it only so that if it fails for someone, they'll know why.)

Regards,
Alister

F=( x y z w )
for FILE in ${F[@]}; do :>$FILE; done # empty files if necessary
while read L
do    echo "$L" >> ${F[$((i%4))]}
       ((i++))
done < A

Nice solution, frans, but note that your read will strip leading and trailing whitespace, as well as discard backslashes and possibly merge lines. To preserve lines as they appear in the original file, you'd want to use:

while IFS= read -r L

---------- Post updated at 07:15 AM ---------- Previous update was at 07:11 AM ----------

A posix sh approach without arithmetic:

set x y z w
while IFS= read -r line; do
    echo "$line" >> $1
    set $@ $1
    shift
done < A

Regards,
Alister

From Guru's solution :

awk -v Files="x,y,z,w" '
BEGIN { nbFiles = split(Files, file, /,/) ; file[0] = file[nbFiles] }
{ print > file[NR % nbFiles ] }
' A

Input file A:

1 x
2 y
3 z
4 w
5 x
6 y
7 z
8 w
9 x

Result files x, y, z and w:

$ cat x
1 x
5 x
9 x
$ cat y
2 y
6 y
$ cat z
3 z
7 z
$ cat w
4 w
8 w
$ 

Jean-Pierre.

That's great !!

Thanks for the response and your help.
Just one small change in my query, I would like to automate this like, I would like to specify the number of out put files through commond promt and I have tried the same but it did not work. it would be great if some one help me to make it work. Thanks in advance.

> set_script.sh 3 inputfile

#!/usr/bin/ksh
nof=$1
file=$2
for ((i=1; i<=nof; i++))
do
sed -n -e '$i~4w $x[i]' $file
done

Regards
Subba

How do you want to name your files?

Would like to name as

GL_Segment1
GL_Segment2
...........

Regards
Subba

Try something like...

$ seq 1 100 > file1

$ awk '{print > f (NR%n?NR%n:n)}' n=3 f="GL_Segment" file1

$ head -4 GL_Segment?
==> GL_Segment1 <==
1
4
7
10

==> GL_Segment2 <==
2
5
8
11

==> GL_Segment3 <==
3
6
9
12

$