如何获取文件中的某一行?

本文最后更新于2014年11月12日,已超过 1 年没有更新,如果文章内容失效,还请反馈给我,谢谢!

在Stackoverflow上看到一个题目”Shell/Bash Command to get nth line of STDOUT“,觉得不错,尝试了其中介绍的方法,然后结合自己之前的一些学习,总结/摘录至下文:

用Linux的命令获取文件中的某一行{Shell/Bash Command to get nth line of STDOUT}

Is there any bash command that will let you get the nth line of STDOUT?
That is to say, something that would take this

and do something like

I realize this would be bad practice when writing scripts meant to be reused, BUT when working with the shell day to day it’d be useful to me to be able to filter my STDOUT in such a way.
I also realize this would be semi-trivial command to write (buffer STDOUT, return a specific line), but I want to know if there’s some standard shell command to do this that would be available without me dropping a script into place.


Using sed, just for variety:

Using this alternative, which looks more efficient since it stops reading the input when the required line is printed, may generate a SIGPIPE in the feeding process, which may in turn generate an unwanted error message:

I’ve seen that often enough that I usually use the first (which is easier to type, anyway), though ls is not a command that complains when it gets SIGPIPE.
For a range of lines:

For several ranges of lines:


Alternative to the nice head / tail way:

or


From sed1line:

From awk1line:


Try this sed version:

It says “delete all the lines that aren’t the second one”.


For the sake of completeness 😉
shorter code

shorter life


Is Perl easily available to you?


Obviously substitute whatever number you want for 7.
You can use awk:

Update
The above code will not get what we want because of off-by-one error: the ls -l command’s first line is the total line. For that, the following revised code will work:


Another poster suggested

but if you pipe head into tail, it looks like everything up to line N is processed twice.
Piping tail into head

would be more efficient?

原文链接:

http://stackoverflow.com/questions/1429556/shell-bash-command-to-get-nth-line-of-stdout


 

快速打印出文件中间位置的行
1.sed和awk

假设你需要20至40行的内容:

2.sed的几种方式(打印/显示指定行)

method 3 efficient on large files

fastest way to display specific lines

3.先head然后tail

在Python中可以现将文件readlines()到一个list中,然后使用list切割方法进行查看——对于小文件而言。

4.先切割,然后分别查看

先split,然后grep、sed、awk、head、tail

参考

声明: 除非注明,ixyzero.com文章均为原创,转载请以链接形式标明本文地址,谢谢!
https://ixyzero.com/blog/archives/1574.html

发表评论

电子邮件地址不会被公开。 必填项已用*标注