Koralkloud
Koralkloud

Reputation: 444

shell script to read the line from one file and sed it in another file

I need to read the value from one file and sed that value in another file.so here is the content of the files

file1.txt

test1.example.com
test2.example.com
test3.example.com

file2.txt

### list of servers ##
[group]
server1  ansible_host=pub_ip1 ansible_user=eadmin  
server2 ansible_host=pub_ip2 ansible_user=eadmin  
server3 ansible_host=pub_ip3 ansible_user=eadmin

so the expected output should be below

file2.txt

    ### list of servers ##
    [group]
    test1.example.com  ansible_host=pub_ip1 ansible_user=eadmin  
    test2.example.com  ansible_host=pub_ip2 ansible_user=eadmin  
    test3.example.com  ansible_host=pub_ip3 ansible_user=eadmin 

the first line of file1 should replace server1 in file2 and so on. I am pretty much new to bash and Linux. it would be great if someone could help me to achieve this.

Thanks in Advance

Upvotes: 0

Views: 369

Answers (1)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

sed -e '/[group]/!b;:a;n;R file1' -e 'ba' file2 |
sed '1,/[group]/b;N;s/\n\S\+\s*/ /'

Interleave file1 with file2 in the first sed invocation.

Pipe the result to a second sed invocation that replaces the first field with the line above for the required replacement.

Upvotes: 1

Related Questions