tags:

views:

45

answers:

2

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

A: 

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.

Matthew Flaschen
That's great. Just for the record at least on my machine if you try to use those single quotes you get an ugly message so ...sed.exe -e :a -e "$q;N;11,$D;ba" in.txt > out.txt... is the way to go.As I mentioned above I didn't know about the coreutils but as you say that would make life easier.... is the way to go.
+2  A: 

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.

ghostdog74
+1 for the suggestion to use the right tools - I couldn't care less myself how to torturously bend `sed` to a task better suited for tail :-)
paxdiablo
I was unaware of the existence of the GNU win32 tools - thanks for the pointer. It would need to capable of working from removeable media (which is how I use sed) but this is usually the case with GNU utilities so it might be a good solution.Other than that (@paxdiablo) Windows does not have a 'tail' ... otherwise I'd use it ;-)
@glaucon. GNU tools are just individual exe files. you just bring all of them into your removable media.
ghostdog74