Chris Noe
Chris Noe

Reputation: 37161

sed line range, all but the last line

You can specify a range of lines to operate on. For example, to operate on all lines, (which is of course the default):

sed -e "1,$ s/a/b/"

But I need to operate on all but the last line. You apparently can't use arithmetic expressions:

sed -e "1,$-1 s/a/b/"

(I am using cygwin in this case, if it makes a difference)

Upvotes: 45

Views: 31391

Answers (5)

Julio
Julio

Reputation: 115

I know it is not sed, but I feel that head gets the easiest and most flexible way:

head -n -1 the-file

Use -2, -3... instead of -1, to retrieve all but the last two lines, etc.

Upvotes: 3

Alejandro Jaliff
Alejandro Jaliff

Reputation: 1

In a more general sense, this issue requires you to edit a stream by specifying a range with one of the range limits being an offset from the end-of-file. The following example shows how to do this. In this example I am printing out all the lines of a file, beginning with the 5th line from the last line, and ending with the last line. In your case, you can set OFFSET = -1instead of OFFSET = -5.

(( OFFSET = -5 )); (( N1 = $(cat pgen.c | wc -l) + OFFSET )); sed -n "$N1,\$p" thefile

This command can be entered in one line.

Upvotes: -1

guerda
guerda

Reputation: 24049

This command works, too

sed '$d'

Upvotes: 19

AdamC
AdamC

Reputation: 16273

sed -e "$ ! s/a/b/"

This will match every line but the last. Confirmed with a quick test!

Upvotes: 66

Adam Rosenfield
Adam Rosenfield

Reputation: 400274

Well, you could hack it with something like this:

sed -e "1,$(($(cat the-file | wc -l) - 1))s/a/b/"

Or, you could use tail instead:

(tail +1 the-file) | sed -e s/a/b/; tail -1 the-file

Upvotes: 1

Related Questions