Nekura Kuroi
Nekura Kuroi

Reputation: 87

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

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

Upvotes: 4

Views: 6518

Answers (3)

PesaThe
PesaThe

Reputation: 7509

Simple ex should do:

ex file <<< $'1,3m$\nw'

Upvotes: 0

John1024
John1024

Reputation: 113924

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.

Upvotes: 13

Jotne
Jotne

Reputation: 41460

Try this using awk

awk '{print $4,$5,$1,$2,$3}' file
STUVWX YZ1234 ABCDEF GHIJKL MNOPQR

PS, this is multiple fields, not lines.

To write it back to the original file

awk '{print $4,$5,$1,$2,$3}' file > tmp && mv tmp file

If data is in this format:

cat file
ABCDEF
GHIJKL
MNOPQR
STUVWX

Then this may do:

awk '{a[NR]=$0} END {print a[4],a[5],a[1],a[2],a[3]}' OFS="\n" file
STUVWX
YZ1234
ABCDEF
GHIJKL
MNOPQR

Upvotes: 0

Related Questions