简体   繁体   English

在 Bash 中的某个特定匹配项下方编辑/匹配字符串 n 行?

[英]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下面是我要编辑的ndxconfig.ini文件

# /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 .我想将马拉松协议配置从 http 更改为 https Not other's protocol conf.不是其他的协议配置。 I have to match PROTOCOL = http 3 lines below the [MARATHON] line.我必须在[MARATHON]下方匹配PROTOCOL = http 3 行。 I researched and couldn't find any solution.我研究并找不到任何解决方案。 There's only 1 line below sed solutions. sed 解决方案下面只有 1 行。

One idea stuck mine was somehow specially grep [MARATHON] and 3 lines below and tail 1 line.我的一个想法特别是 grep [MARATHON]和下面的 3 行和尾 1 行。 I don't know.我不知道。 How can fix this?如何解决这个问题? Please Help.请帮忙。

Solution found here这里找到的解决方案

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

If you have python available, you can use crudini :如果你有python可用,你可以使用crudini

crudini --set ndxconfig.ini MARATHON protocol https

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尖叫,它将文件视为一个整体,而不是像sed那样一次处理一行(并且也不依赖于sed的非posix -i扩展的可用性,用于文件的就地编辑):

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.这将替换块中以匹配 MARATHON 的行开头并以空行结尾的 PROTOCOL 行。 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)如果协议已经是https,它不会做任何事情(除了打印一个问号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM