file1에서 IP를 가져오고 file2에서 업데이트

file1에서 IP를 가져오고 file2에서 업데이트

두 개의 파일이 있습니다. 하나는 다른 파일에서 교체해야 하는 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의 처음 두 줄을 삭제한 후 다음을 수행해야 합니다.

$ 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에서 처음 두 줄을 삭제했습니다. 명령을 붙여넣어 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

그런 다음 이 파일의 줄을 네 부분으로 나눕니다.

(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의 처음 두 줄과 연결하면 됩니다.

관련 정보