Sed: delete all but the last X lines of a file

sed

It can be done with other tools, but I am interested to know how can I delete all but the last X lines of the file with sed.

Best Answer

Basically you are emulating tail. X = 20 in this example. The following example will delete all but the last 20 lines:

sed -i -e :a -e '$q;N;21,$D;ba' filename

Explanation:

  • The -e :a creates a label called a
  • The next -e:
    • $q - quits and prints the pattern space if it is the last line
    • N - next line
    • 21,$D - executes the "D" command if the line# is >= 21 (21,$ = 21st line to $ which is the end of the file)
    • ba - branches to label 'a' which is the beginning of the script.
Related Question