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

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].

Answers


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.


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.


Need Your Help

xcode localization only creates files for Main storyboard

ios xcode swift

I'm trying to localize my application. However when i click the project folder and choose my language i only seem to get the files on Main storyboard. As you can see below the storyboards ain't sho...

BeginForm in Partial View does not fire controller method

jquery asp.net-mvc dialog

My web app is in MVC and I have a .cshtml page with a <form> in it as well as a partial view with @using