Chinaunix

标题: sed如何交换两行? [打印本页]

作者: fwsky    时间: 2007-07-07 22:17
标题: sed如何交换两行?
拿置顶示例来说:
The honeysuckle band played all night long for only $90.
It was an evening of splendid music and company.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.

交换第1和第2行,如何用 h,x 命令写? 我写了下,总是把一行全部覆盖成另一行了。求救!
作者: ly5066113    时间: 2007-07-08 09:54
h,G
作者: fwsky    时间: 2007-07-08 12:21
我是这样的:
      sed -e '1h' -e '2x' -e '1x' quote.txt > xx
本意是:先将第1行复制到hold space,然后将第2行与之交换,最后第1行与之交换
如果正常的话,应该是将1,2行的内容交换好的,不过不知道我对这些命令的理解是否
有问题,总得不到我想要的结果,  cat xx 的输出是:
The honeysuckle band played all night long for only $90.
The honeysuckle band played all night long for only $90.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.
可见,第1行把第2行覆盖了,但是原本第2行内容并没有替换掉第1行。
why?使用命令上哪里要注意什么呢?
作者: 寂寞烈火    时间: 2007-07-08 12:35
try:
sed -e '1h' -e '2G' -e '1d'
作者: fwsky    时间: 2007-07-08 13:16
这个做法,只对交换相邻两行有效,如果不相邻,那么就无法完成交换目的,比如
交换2,4两行:   sed -e '2h' -e '4G' -e '2d' quote.txt       结果是:
The honeysuckle band played all night long for only $90.
Too bad the disco floor fell through at 23:00.
The local nurse Miss P.Neave was in attendance.
It was an evening of splendid music and company.

可见,仅仅将第2行附加到第4行后面,再将第2行移去,然而新的第2行却是原来的第
3行,没有完成我想要的“交换第2行和第4行”。也许通过多次h,G,d可以完成,但
未免太麻烦。
其实这里我想知道的是,man sed 中,关于x命令的说明,就是利用了一个临时“变量”
来交换两行(类似于C中的swap方式),但是却达不到交换的效果。
老大们能否帮我再看看啊! 多谢多谢
作者: ly5066113    时间: 2007-07-08 17:10
x是交换pattern space和hold space,先理解了这个两个space吧。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2