Adil Saju
Adil Saju

Reputation: 1189

Edit/Match a string n lines below some specific match in Bash?

I have a complex problem. Below is the ndxconfig.ini file I want to Edit

# /etc/ndxconfig.ini will override this file
# if APP_ID is added in service propery, service discovery will be using marathon;
# HOST/PORT specified will override values retrieved from marathon

[MARATHON]
HOSTS = {{ ','.join(groups['marathon'])}}
PORT = 8080
PROTOCOL = http
SECRET = SGpQIcjK2P7RYnrdimhhhGg7i8MdmUqwvA2JlzbyujFS4mR8M88svI7RfNWt5rnKy4WHnAihEZmmIUb940bnlYmnu47HdUHE


[MYSQL]
; APP_ID = /neon/infra/mysql
HOST = {{keepalived_mysql_virtual_ip}}
PORT = 3306
SECRET = tIUFN1rjjDBdEXUsOJjPEtdieg8KhwTzierD48JsgDeYc84DD6Uy5a6kzHfKolq1MNS1DKwlSqxENk33UulJd9DPHPzYCxFm

I want to change specifically marathon protocol conf from http to https. Not other's protocol conf. I have to match PROTOCOL = http 3 lines below the [MARATHON] line. I researched and couldn't find any solution. There's only 1 line below sed solutions.

One idea stuck mine was somehow specially grep [MARATHON] and 3 lines below and tail 1 line. I don't know. How can fix this? Please Help.

Upvotes: 0

Views: 106

Answers (3)

Shawn
Shawn

Reputation: 52429

This screams for ed, which treats the file as a whole, not processing it a line at a time like sed (And also doesn't depend on the availability of the non-posix -i extension to sed for in-place editing of files):

ed -s ndxconfig.ini <<'EOF'
/MARATHON/;/^$/ s/^PROTOCOL = http$/PROTOCOL = https/
w
EOF

This will replace the PROTOCOL line in the block that starts with a line matching MARATHON and ending with a blank line. The protocol entry can be the second, third, fourth, etc. line; doesn't matter. If the protocol is already https, it won't do anything (Except print a question mark)

Upvotes: 0

Thor
Thor

Reputation: 47109

If you have python available, you can use crudini:

crudini --set ndxconfig.ini MARATHON protocol https

Upvotes: 1

Corentin Limier
Corentin Limier

Reputation: 5006

Solution found here

sed '/\[MARATHON\]/{N;N;N;s/http/https/;}' <file>

Upvotes: 2

Related Questions