下面是文件
中的数据[dev01]
server7.srv.us.domain.net
server3.srv.us.domain.net
server2.srv.us.domain.net
server1.srv.us.domain.net
[dev02
server5.srv.us.domain.net
我需要grep dev01部分,并插入新的服务器详细信息(server9.srv.us.domain.net)行server1.srv.us.domain.net之后,再次使用shell脚本插入空行
Using awk:
awk -v tag="[dev01]" -v servline="server1.srv.us.domain.net" -v addline="server9.srv.us.domain.net" '$0 ~ tag { found=1 } found==1 && $0 ~ servline { $0=$0"n "addline;found=0 }1' file > file.tmp && mv -f file.tmp file
解释:
awk -v tag="[dev01]" -v servline="server1.srv.us.domain.net" -v addline="server9.srv.us.domain.net"
# Pass tag section to edit as tag, line to insert after a servline and actual line to insert as addline
'$0 ~ tag {
found=1 # If line ($0) pattern matches to tag, set found to 1
}
found==1 && $0 ~ servline {
$0=$0"n "addline; # If found equal 1 and the current line is equal to servline, add a new line and the variable addline to the existing line
found=0 # Reset the found marker
}1' file > file.tmp && mv -f file.tmp file
# Redirect output to temp file and move temp to original to commit the changes
如果您有最新版本的GNU awk,您不需要这样做,可以使用awk -i
使用sed:
sed '/[dev01]/,/[/{s/server1.srv.us.domain.net/server1.srv.us.domain.netn server9.srv.us.domain.net/}' file
搜索从[dev01]到任何带有"["和过程。替代"server1.srv.us.domain.net"加上"server1.srv.us.domain.net"one_answers"server9.srv.us.domain.net"使用-i
提交文件