创建 bash 脚本以从现有的 linux etc/hosts 文件创建 yaml 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41598377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:36:38  来源:igfitidea点击:

Create bash script to create yaml files from existing linux etc/hosts files

bashyamlhosts

提问by atomicsitup

I'm new to scripting but have been tasked with creating yaml files from existing Linux /etc/hosts files. Using a hosts file here:

我是脚本的新手,但我的任务是从现有的 Linux /etc/hosts 文件创建 yaml 文件。在此处使用主机文件:

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

..to create yaml files that look like this:

..创建如下所示的 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'

I know there is more than one way to reach a desired solution. But I'm not quite sure how to script this in a way to get the correct format. Any suggestions would be appreciated.

我知道有不止一种方法可以达到所需的解决方案。但我不太确定如何以某种方式编写脚本以获得正确的格式。任何建议,将不胜感激。

回答by Charles Duffy

Easy and wrong (not strongly guaranteed that output will be valid YAML for all possible inputs):

简单和错误(不强烈保证输出对于所有可能的输入都是有效的 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=; 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

...for something that's shorter and wrong-er, see edit history (prior version also worked for your sample input, but couldn't correctly handle blank lines, comments, IPs with more than one hostname, etc).

...对于较短和错误的内容,请参阅编辑历史记录(先前版本也适用于您的示例输入,但无法正确处理空行、注释、具有多个主机名的 IP 等)。

Given your exact host file as input, this emits:

将您的确切主机文件作为输入,这会发出:

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'