我是脚本新手,但我们的任务是从现有的Linux / etc / hosts文件创建yaml文件。在这里使用hosts文件:
127.0.0.1 localhost
192.168.1.2 host1
192.168.1.3 host2
192.168.1.4 host3
192.168.1.5 host4
..创建如下所示的yaml文件:
host_entries:
host1:
ip: '192.168.1.2'
host2:
ip: '192.168.1.3'
host3:
ip: '192.168.1.4'
host4:
ip: '192.168.1.5'
我知道有多种方法可以达到理想的解决方案。但是我不太确定如何以某种方式编写脚本以获得正确的格式。任何建议将不胜感激。
答案 0 :(得分:3)
简单和错误(并非强烈保证输出对于所有可能的输入都是有效的YAML):
{
printf 'host_entries:\n'
while read -r -a line; do
[[ ${line[0]} ]] || continue # skip blank lines
[[ ${line[0]} = "#"* ]] && continue # skip comments
[[ ${line[0]} = 127.0.0.1 ]] && continue # skip localhost
set -- "${line[@]}" # assign words read from line to current argument list
ip=$1; shift # assign first word from line to ip
for name; do # iterate over other words, treating them as names
printf " %s:\n ip: '%s'\n" "$name" "$ip"
done
done
} </etc/hosts >yourfile.yaml
...对于更短和更错的东西,请参阅编辑历史记录(先前版本也适用于您的示例输入,但无法正确处理空白行,注释,具有多个主机名的IP等)。 / p>
鉴于您确切的主机文件为输入,这将发出:
host_entries:
host1:
ip: '192.168.1.2'
host2:
ip: '192.168.1.3'
host3:
ip: '192.168.1.4'
host4:
ip: '192.168.1.5'