sed - 如何删除除最后 n 行之外的所有内容? [英] sed - how to delete everything but the last n lines?

查看:47
本文介绍了sed - 如何删除除最后 n 行之外的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 sed 的 Windows 框(没有 CYGWIN 等)上,如何从文本文件中删除除最后 n 行之外的所有行"?

On a windows box (no CYGWIN etc) using sed how can you "delete all but the last n lines" from a text file ?

在 *nix 上,您可以使用 tail/cat/wc 来预处理输入文件,但是如何使用纯 sed 来执行此操作?

On *nix you could get tail/cat/wc involved to pre-process the input file but how can you do this using pure sed ?

[FWIW sed 是 GNU sed;平台为Windows 2003].

[FWIW the sed is the GNU sed; the platform is Windows 2003].

推荐答案

来自这个列表sed 单行:

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

在 Windows 上:

On Windows:

sed.exe -e :a -e "$q;N;11,$D;ba"

那个例子是 n = 10.用 n + 1 替换 11.它基本上通过在模式空间中保留一个运行列表来工作.对于前 10 行,它只是附加到模式空间 (N),然后循环到开头.对于 11 及更高版本,它还会删除模式空间的第一行.最后,在 ($) 处,它退出,自动打印最后 n 行.

That example is for n = 10. Replace 11 with n + 1. It basically works by keeping a running list in the pattern space. For the first 10 lines, it just appends to the pattern space (N), then loops to the beginning. For 11 and later, it also deletes the first line of the pattern space. Finally, at the ($), it quits, which automatically prints the final n lines.

不过,这真的不是 sed 的强项.我只想从 gnuwin32 安装 coreutils.

This is really not sed's strong suit, though. I would just install coreutils from gnuwin32.

这篇关于sed - 如何删除除最后 n 行之外的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆