Search code examples
linuxunixsedtail

Move Last Four Lines To Second Row In Text File


I need to move the last 4 lines of a text file and move them to the second row in the text file.

I'm assuming that tail and sed are used but, I haven't much luck so far.


Solution

  • Here is a head and tail solution. Let us start with the same sample file as Glenn Jackman:

    $ seq 10 >file
    

    Apply these commands:

    $ head -n1 file ; tail -n4 file; tail -n+2 file | head -n-4
    1
    7
    8
    9
    10
    2
    3
    4
    5
    6
    

    Explanation:

    • head -n1 file

      Print first line

    • tail -n4 file

      Print last four lines

    • tail -n+2 file | head -n-4

      Print the lines starting with line 2 and ending before the fourth-to-last line.