繁体   English   中英

如何使用sed交换两行?

[英]How can I swap two lines using sed?

有没有人知道如何使用sed编辑器将line a line b替换line a line bline b line a替换为文本文件中的a line a

我可以看到如何用保持空间中的一条线替换模式空间中的一条线(即/^Paco/x/^Paco/g ),但是如果我想从Paco开始的Paco线怎么办? Vinh开头的线替换它,并从Vinh开始用线替换它,用从Paco开始的线替换它?

让我们假设对于初学者来说, Paco一条线, Vinh一条线,并且线条Paco出现在线Vinh之前。 然后我们可以转到一般情况。

#!/bin/sed -f
/^Paco/ {
:notdone
  N
  s/^\(Paco[^\n]*\)\(\n\([^\n]*\n\)*\)\(Vinh[^\n]*\)$/\4\2\1/
  t
  bnotdone
}

匹配后/ ^ Paco /我们读入模式缓冲区直到s //成功(或EOF:模式缓冲区将保持不变)。 然后我们开始搜索/ ^ Paco /。

cat input | tr '\n' 'ç' | sed 's/\(ç__firstline__\)\(ç__secondline__\)/\2\1/g' | tr 'ç' '\n' > output

用您想要的正则__secondline__替换__firstline____secondline__ 一定要替换任何实例. 在你的正则表达式[^ç] 如果你的文字实际上有ç ,用你的文字没有的其他东西替换。

GNU sed texinfo doc中的一个简单示例:

Note that on implementations other than GNU `sed' this script might
easily overflow internal buffers.

 #!/usr/bin/sed -nf

 # reverse all lines of input, i.e. first line became last, ...

 # from the second line, the buffer (which contains all previous lines)
 # is *appended* to current line, so, the order will be reversed
 1! G

 # on the last line we're done -- print everything
 $ p

 # store everything on the buffer again
 h

试试这个awk脚本。

s1="$1"
s2="$2"
awk -vs1="$s1" -vs2="$s2" '
{ a[++d]=$0 }
$0~s1{ h=$0;ind=d}
$0~s2{
 a[ind]=$0
 for(i=1;i<d;i++ ){ print a[i]}
 print h
 delete a;d=0;
}
END{ for(i=1;i<=d;i++ ){ print a[i] } }' file

产量

$ cat file
1
2
3
4
5

$ bash test.sh 2 3
1
3
2
4
5

$ bash test.sh 1 4
4
2
3
1
5

使用sed (或根本不使用)仅用于简单替换。 更复杂的是,使用编程语言

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM