I\'m trying to print every n
th line from file, but n
is not a constant but a variable.
For instance, I want to replace sed -n \'1~5p\'
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
.
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