user1967718
user1967718

Reputation: 985

Print every n lines from a file

I'm trying to print every nth line from file, but n is not a constant but a variable.

For instance, I want to replace sed -n '1~5p' with something like sed -n '1~${i}p'.

Is this possible?

Upvotes: 5

Views: 6853

Answers (4)

fedorqui
fedorqui

Reputation: 289775

awk can also do it in a more elegant way:

awk -v n=YOUR_NUM 'NR%n==1' file

With -v n=YOUR_NUM you indicate the number. Then, NR%n==1 evaluates to true just when the line number is on a form of 7n+1, so it prints the line.

Note how good it is to use awk for this: if you want the lines on the form of 7n+k, you just need to do: awk -v n=7 'NR%n==k' file.

Example

Let's print every 7 lines:

$ seq 50 | awk -v n=7 'NR%n==1'
1
8
15
22
29
36
43
50

Or in sed:

$ n=7
$ seq 50 | sed -n "1~$n p" # quote the expression, so that "$n" is expanded
1
8
15
22
29
36
43
50

Upvotes: 11

NeronLeVelu
NeronLeVelu

Reputation: 10039

why a sed ?

head -${i} YourFile

Upvotes: 0

Kent
Kent

Reputation: 195079

The point is, you should use double quote " instead of the single one to wrap your sed codes. Variable won't be expanded within single quote. so:

sed -n "1~${i} p"

Upvotes: 9

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

You can do it like this for example:

i=3
sed "2,${i}s/.*/changed line/g" InputFile

Example:

AMD$ cat File
aaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccc
ddddddddddddddddddddddd
eeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffff
ggggggggggggggggggggg

AMD$ i=4; sed "2,${i}s/.*/changed line/g" File
aaaaaaaaaaaaaaaaaaaaaaaa
changed line
changed line
changed line
eeeeeeeeeeeeeeeeeeeeeeee
fffffffffffffffffffff
ggggggggggggggggggggg

The key is to use " " for variable substitution.

Upvotes: 1

Related Questions