SED: insert something after the second last line?

To insert a line before the last ($) one:

$ cat test
one
two
three
four
five

$ sed '$i<hello>!' test
one
two
three
four
<hello>!
five

That's for GNU sed (and beware leading spaces or tabs are stripped). Portably (or with GNU sed, if you want to preserve the leading spaces or tabs in the inserted line), you'd need:

sed '$i\
<hello>!' test

Yes, sed can be told to act on only a specific line by writing the line number before the operation you tell it to perform. For example, to insert a line with the string foo after the 4th line of a file, you could do:

sed '4s/$/\nfoo/' file  # GNU sed and a few others
sed '4s/$/\
foo/' file # standardly/portably

To insert a line after the next to last line, I can think of two approaches:

  1. Count the number of lines first and then make the edit:

    sed "$(( $( wc -l < file) -2 ))s/$/\nfoo/" file
    
  2. Use tac:

    tac file | sed '2s/$/\nfoo/' | tac
    

Tags:

Sed