A set of paragraphs of 4 lines to manage with AWK
awk -F[][] -vOFS= '++i==1 {a=$2} i==2 {b=$2} i==3 {$2="[" b "]"} i==4 {$2="[" a "]"} !NF {i=0} 1' input.txt
With square brackets as the field separators, your replacement sources/targets are in $2
.
We increment i
on each line, and reset it to zero between paragraphs. The value of i
(1 though 4) tells us what to do with $2
.
$ cat tst.awk
match($0,/\[.*]/) {
idx = (NR - 1) % 5 + 1
sect[idx] = substr($0,RSTART,RLENGTH)
if ( idx == 3 ) {
$0 = $1 OFS sect[2] OFS $NF
}
else if ( idx == 4 ) {
$0 = $1 OFS sect[1] OFS $NF
}
}
{ print }
$ awk -f tst.awk file
A1 [A3 A4 A5] A2
B1 [B3 B4 B5] B2
C1 [B3 B4 B5] C2
D1 [A3 A4 A5] D2
E1 [E3 E4 E5] E2
F1 [F3 F4 F5] F2
G1 [F3 F4 F5] G2
H1 [E3 E4 E5] H2
The above does string replacement so it'll work even if the sections inside brackets contain regexp metachars or backreferences.