Using SED to Get the Last n Lines of a Huge Text File

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

How can I use "sed" command to get the last n lines of a huge text file (e.g. A.txt) and copy them into a new text file(e.g. B.txt)? I do not want to remove that lines from A.txt.

回答1:

You don't. You use tail -n NUMLINES for that.

tail -n 100 A.txt > B.txt 


回答2:

Here's how to use sed to print the last 10 lines of a file:

sed -e :a -e '$q;N;11,$D;ba'  

You should probably only use this if you're planning on executing more sed commands on these lines. Otherwise the tail command is designed for this job.



回答3:

Using GNU sed, here's how to get the last 10 lines:

(For n lines, replace 11, with n+1)

sed -ne':a;$p;N;11,$D;ba' A.txt > B.txt

Note: On my Mac, with MacPorts, GNU sed is invoked as gsed. To use Apple's sed you would have to separate the label: sed -ne':a' -e'$p;N;11,$D;ba'*

Explanation:

sed -ne' invoke sed without automatic printing pattern space

:a label for looping

$p on last line, print pattern space, then quit

N slurp the next line

11,$D on line 11 through last line, remove the first line from pattern space (i.e. [^\n]*\n)

ba' loop to :a

Further

Because of the loop, sed continuously appends the next line to pattern space. After line 11 and through the last line (11,$D) sed begins removing the first line from pattern space. At the last line the pattern space is printed (`$p'), which contains the last 10 most recently slurped lines (the last 10 lines of file A.txt).



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!