insert before each match using awawk, sed or bash

I want to change the file with the following contents:

[Peer]
PublicKey = gpS4RheuHn+/RIyT+H2Eur3nPxOKxSLDXPtyt1vqFAg=
AllowedIPs = 10.0.0.2/32

[Peer]
PublicKey = 8j/QYgGxeqMNRrKe5V/yQpBf8k8gX63bDBmeuKWhDTY=
AllowedIPs = 10.0.0.3/32

[Peer]
PublicKey = 6lcI+cBb79SS1v60kG63QPvoHvegP1ESqOjeZReUBwo=
AllowedIPs = 10.0.0.4/32

[Peer]
PublicKey = UqMYp8SbLvdnRpWG9t3Ve9SMKvmASnWE0w0XIe9XGQc=
AllowedIPs = 10.0.0.5/32

[Peer]
PublicKey = S7bbWxHECZfbnzJrDGcQOvGHq4/E7rAn4LAemtrDnRs=
AllowedIPs = 10.0.0.6/32

[Peer]
PublicKey = rSu3IGLcSZTiWTPyBRC0U12N5Ho6TMIHVfXu2An7Fyo=
AllowedIPs = 10.0.0.7/32

to

# Peer: 1
[Peer]
PublicKey = gpS4RheuHn+/RIyT+H2Eur3nPxOKxSLDXPtyt1vqFAg=
AllowedIPs = 10.0.0.2/32

# Peer: 2
[Peer]
PublicKey = 8j/QYgGxeqMNRrKe5V/yQpBf8k8gX63bDBmeuKWhDTY=
AllowedIPs = 10.0.0.3/32

# Peer: 3
[Peer]
PublicKey = 6lcI+cBb79SS1v60kG63QPvoHvegP1ESqOjeZReUBwo=
AllowedIPs = 10.0.0.4/32

# Peer: 4
[Peer]
PublicKey = UqMYp8SbLvdnRpWG9t3Ve9SMKvmASnWE0w0XIe9XGQc=
AllowedIPs = 10.0.0.5/32

# Peer: 5
[Peer]
PublicKey = S7bbWxHECZfbnzJrDGcQOvGHq4/E7rAn4LAemtrDnRs=
AllowedIPs = 10.0.0.6/32

# Peer: 6
[Peer]
PublicKey = rSu3IGLcSZTiWTPyBRC0U12N5Ho6TMIHVfXu2An7Fyo=
AllowedIPs = 10.0.0.7/32

I tried with:

awk '/[Peer]/{print "# Peer: "++c} 1'

but doesn’t work. Many double output.

I want to insert a word # Peer: sequence number before each match.

I try with awk, it gives me many double output.

>Solution :

try with awk ‘/[Peer]/{print "# Peer: "++c}1’ but doest work. Many
double output.

You have forgotten about escaping [ and ], /[Peer]/ means any line containing P or e or e or r, add \ escape sequences that is do

/\[Peer\]/{print "# Peer: "++c}1

and your code should work as intended, though keep in mind that this will check if line contain [Peer] anywhere, if you wish to limit to [Peer] spanning whole line do

$0=="[Peer]"{print "# Peer: "++c}1

Leave a Reply