gpt4 book ai didi

linux - 操作 AWK 字段变量 ($1,$2,..) 并将其添加到行尾

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:02:52 25 4
gpt4 key购买 nike

我正在尝试从 ansible list 文件创建/etc/host 文件。

Ansible list 文件如下所示:

[masters]
k8s-master-a.example.com ansible_ssh_host=10.15.90.2
k8s-master-b.example.com ansible_ssh_host=10.15.90.3
k8s-master-c.example.com ansible_ssh_host=10.15.90.4
[etcd]
k8s-etcd-a.example.com ansible_ssh_host=10.15.91.2
k8s-etcd-b.example.com ansible_ssh_host=10.15.91.3
k8s-etcd-c.example.com ansible_ssh_host=10.15.91.4

以下脚本将有助于使用 fqdn 条目创建它。

$cat inventory.yaml | grep -v '^\[' | sed 's/ansible_ssh_host=//g' | awk '{ print $2 " " $1}' > /etc/hosts
10.15.90.2 k8s-master-a.example.com  
10.15.90.3 k8s-master-b.example.com
10.15.90.4 k8s-master-c.example.com
10.15.91.2 k8s-etcd-a.example.com
10.15.91.3 k8s-etcd-b.example.com
10.15.91.4 k8s-etcd-c.example.com

但我想在/etc/hosts 文件中同时包含 k8s-master-* 和 k8s-etcd-*。最终结果应如下所示。

10.15.90.2 k8s-master-a.example.com k8s-master-a
10.15.90.3 k8s-master-b.example.com k8s-master-b
10.15.90.4 k8s-master-c.example.com k8s-master-c
10.15.91.2 k8s-etcd-a.example.com k8s-etcd-a
10.15.91.3 k8s-etcd-b.example.com k8s-etcd-b
10.15.91.4 k8s-etcd-c.example.com k8s-etcd-c

最佳答案

你只需要 awk 就可以了。这将完成工作:

cat inventory.yaml 
[masters]
k8s-master-a.example.com ansible_ssh_host=10.15.90.2
k8s-master-b.example.com ansible_ssh_host=10.15.90.3
k8s-master-c.example.com ansible_ssh_host=10.15.90.4
[etcd]
k8s-etcd-a.example.com ansible_ssh_host=10.15.91.2
k8s-etcd-b.example.com ansible_ssh_host=10.15.91.3
k8s-etcd-c.example.com ansible_ssh_host=10.15.91.4

awk -F'[[:space:]=]' '/^[^[]/ {split($1, tokens, /[.]/); print $3, $1, tokens[1]}' inventory.yaml
10.15.90.2 k8s-master-a.example.com k8s-master-a
10.15.90.3 k8s-master-b.example.com k8s-master-b
10.15.90.4 k8s-master-c.example.com k8s-master-c
10.15.91.2 k8s-etcd-a.example.com k8s-etcd-a
10.15.91.3 k8s-etcd-b.example.com k8s-etcd-b
10.15.91.4 k8s-etcd-c.example.com k8s-etcd-c

关于linux - 操作 AWK 字段变量 ($1,$2,..) 并将其添加到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55824332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com