Linux 使用 SED 获取大型文本文件的最后 n 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18453328/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:40:29  来源:igfitidea点击:

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

linuxtextsed

提问by user2517676

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.

如何使用“sed”命令获取巨大文本文件(例如 A.txt)的最后 n 行并将它们复制到新文本文件(例如 B.txt)中?我不想从 A.txt 中删除这些行。

采纳答案by user2517676

You don't. You use tail -n NUMLINESfor that.

你没有。你用tail -n NUMLINES那个。

tail -n 100 A.txt > B.txt

回答by dcaswell

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

以下是如何使用 sed 打印文件的最后 10 行:

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 tailcommand is designed for this job.

如果您计划在这些行上执行更多 sed 命令,您可能只应该使用它。否则,该tail命令专为此作业而设计。

回答by parleer

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

使用 GNU sed,以下是获取最后 10 行的方法:

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

(对于 n 行,将 11 替换为 n+1)

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

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 sedyou would have to separate the label: sed -ne':a' -e'$p;N;11,$D;ba'*

注意:在我的 Mac 上,使用 MacPorts,GNU sed 被调用为gsed. 要使用 Apple 的,sed您必须将标签分开:sed -ne':a' -e'$p;N;11,$D;ba'*

Explanation:

解释:

sed -ne'invoke sed without automatic printing pattern space

sed -ne'在没有自动打印模式空间的情况下调用 sed

:alabel for looping

:a循环标签

$pon last line, print pattern space, then quit

$p在最后一行,打印模式空间,然后退出

Nslurp the next line

N吞下下一行

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

11,$D在第 11 行到最后一行,从模式空间中删除第一行(即 [^\n]*\n)

ba'loop to :a

ba'循环到 :a

Further

更远

Because of the loop, sedcontinuously appends the next line to pattern space. After line 11 and through the last line (11,$D) sedbegins 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).

由于循环,sed不断地将下一行附加到模式空间。在第 11 行之后到最后一行 ( 11,$D)sed开始从模式空间中删除第一行。在最后一行打印模式空间(`$p'),其中包含最近 10 行(文件 A.txt 的最后 10 行)。