Insert text N lines before the last line

awkedsedtext processing

I want to insert a new line in two lines before the last line. So if my original file is:

1
2
3
4
5

The result should be

1
2
3
New line
4
5

Best Answer

Using ed:

$ printf '$-1i\nNew line\n.\n,p\n' | ed -s file
1
2
3
New line
4
5

The ed editing script:

$-1i
New line
.
,p

This first moves to the line one line up from the end ($-1) and inserts (i) new contents above that line. The contents inserted is ended with the single dot (it's allowed to be multiple lines). The last ,p displays the complete modified buffer on the terminal.

You may redirect this to a new file, or you may write it back to the original file using

printf '$-1i\nNew line\n.\nw\n' | ed -s file

(the ,p is changed to w).

This latter is also how you would similarly use ex for this job:

printf '$-1i\nNew line\n.\nw\n' | ex -s file

ed and ex are standard line-oriented editors (as opposed to full-screen editors) that should come with your system. Note that -s means different things to each, but is appropriate for both when doing batch mode editing tasks like this.

  • ed. "Shell and utilities". Base specifications. IEEE 1003.1:2017. The Open Group.
  • ex. "Shell and utilities". Base specifications. IEEE 1003.1:2017. The Open Group.

Further reading:

Related Question