Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SED: Move multiple lines to the end of a text file

Tags:

sed

lines

I want to move multiple lines using SED to the end of a file. For example:

ABCDEF
GHIJKL
MNOPQR
STUVWX
YZ1234

should become:

STUVWX
YZ1234
ABCDEF
GHIJKL
MNOPQR
like image 696
Nekura Kuroi Avatar asked Nov 15 '25 14:11

Nekura Kuroi


1 Answers

The question asks a method for using sed to move multiple lines. Although the question, as currently edited, does not show multiple lines, I will assume that they are actually meant to be separate lines.

To use sed to move the first three lines to the end:

$ cat file
ABCDEF
GHIJKL
MNOPQR
STUVWX
YZ1234
$ sed '1,3{H;d}; ${p;x;s/^\n//}' file  
STUVWX
YZ1234
ABCDEF
GHIJKL
MNOPQR

Explanation:

  • 1,3{H;d}

    The 1,3 restricts these commands to operation only on lines 1 through 3. H tells sed to save the current line to the hold buffer. d tells sed not to print the current line at this time.

  • ${p;x;s/^\n//}

    The $ restricts this command to the last line. The p tells sed to print the last line. x exchanges the pattern buffer and hold buffer. The lines that we saved from the beginning of the file are now in the ready to be printed. Before printing, though, we remove the extraneous leading newline character.

  • Before continuing to the next line, sed will print anything left in the pattern buffer.

If you are on Mac OSX or other BSD platform, try:

sed -e '1,3{H;d;}' -e '${p;x;s/^\n//;}' file  

Using head and tail

If you are already familiar with head and tail, this may be a simpler way of moving the first three lines to the end:

$ tail -n+4 file; head -n3 file
STUVWX
YZ1234
ABCDEF
GHIJKL
MNOPQR

Alternative sed command

In the comments, potong suggests:

$ sed '1,3{1h;1!H;d};$G' file
STUVWX
YZ1234
ABCDEF
GHIJKL
MNOPQR

The combination of h, H, and G commands eliminate the need for a substitution command to remove the extra newline.

like image 100
John1024 Avatar answered Nov 18 '25 21:11

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!