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

Time:02-24

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

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

CodePudding user response:

There is no need for sed here. Simply discard the first column from the second file, and paste the results next to each other.

paste file1.txt <(cut -f2- file2.txt)

The <(command) process substitution is a Bash feature, and not generally portable to other shells. A portable equivalent is

cut -f2- file2.txt |
paste file1.txt -

This assumes your second file is tab-delimited; it should be fairly obvious how to adapt this if not.

CodePudding user response:

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.

  • Related