tags:

views:

65

answers:

4

How do I choose even numbered rows of a file? I wish to select rows #2, 4, 6, etc. from a file that contains data. Can anyone help me with this?

+5  A: 
sed -n 'n;p' filename
Mark Byers
+2  A: 

An awk example (as an alternative to Mark's sed example):

awk 'NR % 2 == 0' filename

Example:

$ cat filename
line 0
line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8

$ awk 'NR % 2 == 0' filename
line 1
line 3
line 5
line 7
Rob Hruska
I just updated it.
Rob Hruska
`awk '(NR + 1) % 2 ' filename`
Dennis Williamson
It also depends on how you're considering your line indices (whether or not you want the first line to be 0 or 1).
Rob Hruska
The OP said "#2", etc., so that would mean starting on the second (one-indexed) or **third** (zero-indexed) line. Both your updated `NR % 2 == 0` version and my comment `(NR + 1) % 2` start on the second (one-indexed) line.
Dennis Williamson
+1  A: 

With awk:

awk '{getline;print}' filename

With bash:

#!/bin/bash
while read line
do
    read line
    echo $line
done < filename
Dennis Williamson
better to put -r with read
ghostdog74
+1  A: 

If your sed is GNU's:

sed -n 2~2p filename
Idelic