bash 读取由行号指定的两行之间的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9234788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read lines between two lines specified by their line number
提问by Mechaflash
How would I go about reading all lines between two specific lines?
我将如何阅读两条特定行之间的所有行?
Lets say line 23 is where I want to start, and line 56 is the last line to read, but it is not the end of the file.
假设第 23 行是我想要开始的地方,第 56 行是要读取的最后一行,但它不是文件的结尾。
How would I go about reading lines 23 thru 56? I will be outputting them to another file.
我将如何阅读第 23 至 56 行?我会将它们输出到另一个文件。
回答by Kevin
By row number like that is quite easy with awk:
像这样的行号很容易使用awk:
awk 'NR >= 23 && NR <= 56'
And either way, sedmakes it fun.
无论哪种方式,sed都让它变得有趣。
sed '23,56!d'
Or for a pattern,
或者对于一个模式,
sed '/start/,/end/!d'
回答by Oleg Mikheev
Sed can do that:
Sed 可以做到:
$ sed -n 23,56p yourfile
$ sed -n 23,56p yourfile
EDIT: as commenters pointed out making sed stop processing after the last line of the interval will make sed perform as fast as head-tail combination. So the most optimal way of getting the lines would be
编辑:正如评论者所指出的,在间隔的最后一行之后使 sed 停止处理将使 sed 的执行速度与头尾组合一样快。所以获得线条的最佳方式是
$ sed -n '23,56p;57q' yourfile
$ sed -n '23,56p;57q' yourfile
But performance will greatly depend on the file you're processing, the interval and lots of other factors. So in case you're developing some script to be run frequently on known data testing all three methods mentioned in answers (sed, awk, head-tail) would be a good idea.
但是性能在很大程度上取决于您正在处理的文件、时间间隔和许多其他因素。因此,如果您正在开发一些脚本以在已知数据上频繁运行测试答案中提到的所有三种方法(sed、awk、head-tail)将是一个好主意。
回答by user unknown
I would go for sed, but a head/tail combination is possible as well:
我会选择 sed,但头/尾组合也是可能的:
head -n 56 file | tail -n $((56-23))
head -n 56 file | tail -n $((56-23))
Well - I'm pretty sure there is an off-by-one-error inside. I'm going to find it. :)
好吧 - 我很确定里面有一个逐个错误。我要去找。:)
Update:
更新:
Haha - know your errors, I found it:
哈哈 - 知道你的错误,我发现了:
head -n 56 file | tail -n $((56-23+1))
回答by Harry Forbess
use sed. This should do it.
使用 sed。这应该做。
sed -n '23,56p' > out.txt
回答by potong
This might work for you:
这可能对你有用:
sed '1,22d;56q' file
or this:
或这个:
sed '23,56!d;56q' file
or this:
或这个:
awk 'NR>56{exit};NR==23,NR==56' file

