多行附加/替换之前的 sed 模式搜索

多行附加/替换之前的 sed 模式搜索

我有一个在其上运行的服务器和服务的列表,并且希望将服务器名称作为前缀附加到以下服务

考虑以下输入

"SERVER": "us-east-1e-421"
"SERVICES.SNMP.STATUS": "ok"
"SERVICES.NTP.LATENCY": "1.644"
"SERVICES.POSTFIX.STATUS": "ok"
"SERVER": "us-west-1c-353"
"SERVICES.SNMP.STATUS": "ok"
"SERVICES.NTP.STATUS": "ok"
"SERVICES.NTP.LATENCY": "1.541"
"SERVICES.RSYNC.STATUS": "ok"
"SERVICES.NGINX.STATUS": "ok"

所以我想要的是

us-east-1e-421 SERVICES.SNMP.STATUS ok
us-east-1e-421 SERVICES.NTP.LATENCY 1.644
us-east-1e-421 SERVICES.POSTFIX.STATUS ok
us-west-1c-353 SERVICES.SNMP.STATUS ok
us-west-1c-353 SERVICES.NTP.STATUS ok
us-west-1c-353 SERVICES.NTP.LATENCY 1.541
us-west-1c-353 SERVICES.RSYNC.STATUS ok
us-west-1c-353 SERVICES.NGINX.STATUS ok

我可以使用基本 sed 进行单行或基本搜索/替换,并且我尝试阅读之前发布的一些 sed 指南,例如https://docstore.mik.ua/orelly/unix/sedawk/appa_03.htm 但这对于我的知识来说太过分了,需要一些帮助

sed '/([az]-[阿兹]-[a-z0-9]-[0-9])/ N; s/\n"/\1 /g'

答案1

选择awk解决方案:

awk -F': ' '{ gsub(/"/,"") }/SERVER/{ s=$2; next }{ print s, $1, $2 }' file

输出:

us-east-1e-421 SERVICES.SNMP.STATUS ok
us-east-1e-421 SERVICES.NTP.LATENCY 1.644
us-east-1e-421 SERVICES.POSTFIX.STATUS ok
us-west-1c-353 SERVICES.SNMP.STATUS ok
us-west-1c-353 SERVICES.NTP.STATUS ok
us-west-1c-353 SERVICES.NTP.LATENCY 1.541
us-west-1c-353 SERVICES.RSYNC.STATUS ok
us-west-1c-353 SERVICES.NGINX.STATUS ok

答案2

使用 gnu sed 4.4

sed -E '
/SERVER/{
  s/.* "([^"]*)"/\1/
  h
  d
}
s/[:"]//g
G
s/([^\n]*)\n(.*)/\2 \1/
' infile

答案3

我已经使用 sed 命令来实现相同的效果,并且效果很好

  i=$(sed -n '/us-/p' filename  | awk -F ":" '{print $2}' | sed 's/"//g'  | sed -n '1p' | sed '/^$/d' | sed -r "s/\s+//g")

 j=$(sed -n '/us-/p' filename | awk -F ":" '{print $2}' | sed 's/"//g'  | sed -n '2p' | sed '/^$/d' | sed -r "s/\s+//g")

 sed -n "/$i/,/$j/p" filename  | sed '$d'|sed '1d' |sed "s/SERVER//g" | sed 's/"//g' | sed 's/://g'|sed "s/^/$i /g";sed -n "/$j/,/,/p" o.txt  | sed '1d' |sed "s/SERVER//g" | sed 's/"//g' | sed 's/://g'|sed "s/^/$j /g"

输出

us-east-1e-421 SERVICES.SNMP.STATUS ok
us-east-1e-421 SERVICES.NTP.LATENCY 1.644
us-east-1e-421 SERVICES.POSTFIX.STATUS ok
us-west-1c-353 SERVICES.SNMP.STATUS ok
us-west-1c-353 SERVICES.NTP.STATUS ok
us-west-1c-353 SERVICES.NTP.LATENCY 1.541
us-west-1c-353 SERVICES.RSYNC.STATUS ok
us-west-1c-353 SERVICES.NGINX.STATUS ok

相关内容