Bash工具从文件中获取第n行 [英] Bash tool to get nth line from a file
问题描述
有没有一种规范"的方式来做到这一点?我一直在使用 head -n |tail -1
可以解决问题,但我一直想知道是否有专门从文件中提取一行(或一系列行)的 Bash 工具.
Is there a "canonical" way of doing that? I've been using head -n | tail -1
which does the trick, but I've been wondering if there's a Bash tool that specifically extracts a line (or a range of lines) from a file.
我所说的规范"是指一个主要功能就是这样做的程序.
By "canonical" I mean a program whose main function is doing that.
推荐答案
head
和带有 tail
的管道对于大文件来说会很慢.我建议 sed
像这样:
head
and pipe with tail
will be slow for a huge file. I would suggest sed
like this:
sed 'NUMq;d' file
其中NUM
是要打印的行号;因此,例如,sed '10q;d' file
打印 file
的第 10 行.
Where NUM
is the number of the line you want to print; so, for example, sed '10q;d' file
to print the 10th line of file
.
说明:
NUMq
当行号为NUM
时会立即退出.
NUMq
will quit immediately when the line number is NUM
.
d
将删除该行而不是打印它;这在最后一行被禁止,因为 q
导致退出时跳过脚本的其余部分.
d
will delete the line instead of printing it; this is inhibited on the last line because the q
causes the rest of the script to be skipped when quitting.
如果变量中有 NUM
,则需要使用双引号而不是单引号:
If you have NUM
in a variable, you will want to use double quotes instead of single:
sed "${NUM}q;d" file
这篇关于Bash工具从文件中获取第n行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!