打印文件中的每n行 [英] Print every n lines from a file

查看:80
本文介绍了打印文件中的每n行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从文件中打印第n行,但是n不是常量而是变量.

I'm trying to print every nth 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆