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

旧巷老猫 提交于 2019-12-24 15:20:07

问题


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

回答1:


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.




回答2:


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



回答3:


Simple ex should do:

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


来源:https://stackoverflow.com/questions/26433652/sed-move-multiple-lines-to-the-end-of-a-text-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!