开发者

How can I swap two lines using sed?

Does anyone know how to replace line a with line b and line b with line a in a text file using the sed editor?

I can see how to replace a line in the pattern space with a line that is in the hold space (i.e., /^Paco/x or /^Paco/g), but what if I want to take the line starting with Paco and replace it with the line starting with Vinh, and also take the line starting with Vinh and replace it with the line starting with Paco?

Let's assume for starters that there is one line with Paco and one line with Vinh, and that the lin开发者_开发问答e Paco occurs before the line Vinh. Then we can move to the general case.


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

After matching /^Paco/ we read into the pattern buffer until s// succeeds (or EOF: the pattern buffer will be printed unchanged). Then we start over searching for /^Paco/.


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

Replace __firstline__ and __secondline__ with your desired regexps. Be sure to substitute any instances of . in your regexp with [^ç]. If your text actually has ç in it, substitute with something else that your text doesn't have.


try this awk script.

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

output

$ 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

Use sed (or not at all) for only simple substitution. Anything more complicated, use a programming language


A simple example from the 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜