
2つのファイルがあります。 1つには、別のファイルで置き換える必要があるIPのリストが含まれています。私のファイルは次のとおりです。
ファイル1.txt
173.43.24.67
170.34.24.59
172.83.47.83
160.28.39.49
ファイル2.txt
### HostList ##
[group]
dev ansible_host=pub_ip1 ansible_user=ubuntu
test ansible_host=pub_ip2 ansible_user=ubuntu
prod ansible_host=pub_ip3 ansible_user=ubuntu
uat ansible_host=pub_ip4 ansible_user=ubuntu
期待される出力
### HostList ##
[group]
dev ansible_host=173.43.24.67 ansible_user=ubuntu
test ansible_host=170.34.24.59 ansible_user=ubuntu
prod ansible_host= 172.83.47.83 ansible_user=ubuntu
uat ansible_host=160.28.39.49 ansible_user=ubuntu
上記の目標を達成するために誰かが助けることができれば良いでしょう。
答え1
まず、file2.txtの最初の2行を削除してから、次の操作を行う必要があります。
$ paste file1.txt file2.txt | tr '=' ' ' | awk '{printf("%s %s=%s %s\n",$2,$3,$1,$5)}' | column -t
dev ansible_host=173.43.24.67 ansible_user
test ansible_host=170.34.24.59 ansible_user
prod ansible_host=172.83.47.83 ansible_user
uat ansible_host=160.28.39.49 ansible_user
答え2
これはどこでも機能します。
awk '
NR == FNR {m[NR]=$0}
NR != FNR && f {
sub(/=.*/, "=" m[NR-FNR], $2)
print
}
NR != FNR && !f {
print
if (/^[[]/) f = 1
}
' file1 file2
答え3
$ awk 'NR==FNR{ips[NR]=$1; next} FNR>2{sub(/=[^ ]+/,"="ips[FNR-2])} 1' file1.txt file2.txt
### HostList ##
[group]
dev ansible_host=173.43.24.67 ansible_user=ubuntu
test ansible_host=170.34.24.59 ansible_user=ubuntu
prod ansible_host=172.83.47.83 ansible_user=ubuntu
uat ansible_host=160.28.39.49 ansible_user=ubuntu
答え4
最初の答えに基づいて別のsedです。
paste <(sed -n '3,$p' file2.txt ) file1.txt |sed "s/\(^.*=\)\(pub_ip.\)\(.*\)\t\(.*\)/\1\4\3/"| cat <(head -2 file2.txt) -
出力:
### HostList ##
[group]
dev ansible_host=173.43.24.67 ansible_user=ubuntu
test ansible_host=170.34.24.59 ansible_user=ubuntu
prod ansible_host=172.83.47.83 ansible_user=ubuntu
uat ansible_host=160.28.39.49 ansible_user=ubuntu
編集する:
paste <(sed -n '3,$p' file2.txt ) file1.txt |sed "s/\(^.*=\)\(pub_ip[[:digit:]]*\)\(.*\)\t\(.*\)/\1\4\3/"| cat <(head -2 file2.txt) -
pub_ip 部分の後には、任意の数字を選択しようとします。
説明する。
<(sed -n '3,$p' file2.txt )
file2から最初の2行を削除しました。コマンドを貼り付けてfile1とマージします。
出力paste <(sed -n '3,$p' file2.txt ) file1.txt
:
dev ansible_host=pub_ip1 ansible_user=ubuntu 173.43.24.67
test ansible_host=pub_ip2 ansible_user=ubuntu 170.34.24.59
prod ansible_host=pub_ip3 ansible_user=ubuntu 172.83.47.83
uat ansible_host=pub_ip14 ansible_user=ubuntu 160.28.39.49
次に、このファイルの行を4つの部分に分割します。
(dev ansible_host=) 1st
(pub_ip[digits]) 2nd
( ansible_user=ubuntu) 3rd (plus tab)
173.43.24.67 4th.
そしてパート1、4、3を印刷します。出力:
dev ansible_host=173.43.24.67 ansible_user=ubuntu
test ansible_host=170.34.24.59 ansible_user=ubuntu
prod ansible_host=172.83.47.83 ansible_user=ubuntu
uat ansible_host=160.28.39.49 ansible_user=ubuntu
=>この出力をfile2の最初の2行に関連付けます。