打印文件中的每n行 [英] Print every n lines from a file
问题描述
我正在尝试从文件中打印第n
行,但是n
不是常量而是变量.
I'm trying to print every n
th line from file, but n
is not a constant but a variable.
例如,我想用sed -n '1~${i}p'
之类的东西替换sed -n '1~5p'
.
For instance, I want to replace sed -n '1~5p'
with something like sed -n '1~${i}p'
.
这可能吗?
推荐答案
awk
也可以以更优雅的方式做到这一点:
awk
can also do it in a more elegant way:
awk -v n=YOUR_NUM 'NR%n==1' file
使用-v n=YOUR_NUM
指示数字.然后,仅当行号采用7n+1
形式时,NR%n==1
的计算结果才为true,因此它会打印行.
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.
请注意,将awk
用于此用途有多好:如果要以7n+k
形式显示行,则只需执行:awk -v n=7 'NR%n==k' file
.
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
.
每7行打印一次:
$ seq 50 | awk -v n=7 'NR%n==1'
1
8
15
22
29
36
43
50
或在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
这篇关于打印文件中的每n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!