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
Using SED to Get the Last n Lines of a Huge Text File
提问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 NUMLINES
for 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 tail
command 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 sed
you 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
:a
label for looping
:a
循环标签
$p
on last line, print pattern space, then quit
$p
在最后一行,打印模式空间,然后退出
N
slurp the next line
N
吞下下一行
11,$D
on 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, 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).
由于循环,sed
不断地将下一行附加到模式空间。在第 11 行之后到最后一行 ( 11,$D
)sed
开始从模式空间中删除第一行。在最后一行打印模式空间(`$p'),其中包含最近 10 行(文件 A.txt 的最后 10 行)。