SED:将多行移动到文本文件的末尾 [英] SED: Move multiple lines to the end of a text file

查看:471
本文介绍了SED:将多行移动到文本文件的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SED将多行移至文件的结尾.例如:

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

ABCDEF
GHIJKL
MNOPQR
STUVWX
YZ1234

应成为:

STUVWX
YZ1234
ABCDEF
GHIJKL
MNOPQR

推荐答案

问题提出了一种使用sed移动多条的方法.尽管当前编辑的问题没有显示多行,但我将假定它们实际上是分开的行.

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.

要使用sed将前三行移到末尾:

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

说明:

  • 1,3{H;d}

1,3将这些命令限制为仅在第1至3行上运行.H告诉sed将当前行保存到保持缓冲区. d告诉sed此时不要打印当前行.

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//}

$将此命令限制为最后一行. p告诉sed打印最后一行. x交换模式缓冲区和保持缓冲区.从文件开头保存的行现在可以打印了.不过,在打印之前,我们会删除多余的前导换行符.

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.

在继续下一行之前,sed将打印出模式缓冲区中剩余的所有内容.

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

如果您使用的是Mac OSX或其他BSD平台,请尝试:

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

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

使用头和尾

如果您已经熟悉headtail,这可能是将前三行移到末尾的更简单方法:

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

替代sed命令

在评论中,potong建议:

Alternative sed command

In the comments, potong suggests:

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

hHG命令的组合消除了使用替换命令来删除多余换行符的需要.

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

这篇关于SED:将多行移动到文本文件的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆