开发者

sed - how to delete everything but the last n lines?

开发者 https://www.devze.com 2023-01-05 22:18 出处:网络
On a windows box (no CYGWIN etc) using sed how can you \"delete all but the last n lines\" from a text file ?

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

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 the sed is the GNU sed; the platform is Windows 2003].


if you look at the GNU sed info page, you can see example of using sed's tail version

4.13 Printing the Last Lines
============================

Printing the last N lines rather than the first is more complex but
indeed possible.  N is encoded in the second line, before the bang
character.

   This script is similar to the `tac' script in that it keeps the
final output in the hold space and prints it at the end:

     #!/usr/bin/sed -nf

     1! {; H; g; }
     1,10 !s/[^\n]*\n//
     $p
     h

But why do you want to use sed instead of tail and making your life complicated? Use the most suitable tool for the job. FYI, you can download GNU win32 tools as well.


From this list of sed one-liners:

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

On Windows:

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

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.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消