vkaul11
vkaul11

Reputation: 4214

how to print every fifth row in a file

I have a file with numbers

20
18
21
16
14
30
40
24

and I need to output four files with rows printed with intervals of 4 So we have rows 1,5,9...

20
14

Then rows 2,6,10...

18
30

Then 3,7,11...

21
40

and then 4,8,12...

16 
24

I did try the code below but it does not give me the control over the starting row

awk 'NR % 4 == 0'

Upvotes: 1

Views: 85

Answers (4)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed -ne '1~4w file1' -e '2~4w file2' -e '3~4w file3' -e '4~4w file4' file

Upvotes: 0

Walter A
Walter A

Reputation: 20002

IMHO awk is the best solution. You can use sed:
Inputfile generated with seq 12:

for ((i=1;i<5; i++)); do 
   sed -n $i~4w$i.out <(seq 12)
done

Here w$i.out writes to file $i.out.

Upvotes: 0

kvantour
kvantour

Reputation: 26481

In a single awk you can do:

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

This will send the output to files file0, file1, file2 and file3

Upvotes: 3

anubhava
anubhava

Reputation: 785156

You may use these awk commands:

awk -v n=1 'NR%4 == n%4' file
20
14

awk -v n=2 'NR%4 == n%4' file
18
30

awk -v n=3 'NR%4 == n%4' file
21
40

awk -v n=4 'NR%4 == n%4' file
16
24

Upvotes: 1

Related Questions