How can I swap two lines with sed?

Does anyone know how to replace line awith line band line bon line ain a text file using sed editor?

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

Assume for starters that there is one line with Pacoand one line with Vinhand that the line Pacoappears before the line Vinh. Then we can move on to the general case.

+3
source share
4 answers
#!/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 template buffer until s // is successful (or EOF: the template buffer will be printed unchanged). Then we start by searching for / ^ Paco /.

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

Replace __firstline__with __secondline__your desired regular expressions. Be sure to replace all instances .in your regex [^ç]. If your text actually has çin it, replace something else that your text does not have.

+2
source

GNU sed texinfo:

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

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

$ 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 ( ) . - ,

0

Source: https://habr.com/ru/post/1770819/


All Articles