DomainsFeatured DomainsFeatured - 1 year ago 142
Linux Question

How To Prepend String Only If Match Found Between Two Files

I'm working on a couple files that contain urls. I have tried using sed, cut and grep, but I'm really unsure of how to approach this. If you could just get me moving in the right direction, I would really appreciate it.

File 1:

File 2:

Desired output:

My approach:

I'm thinking I can use grep with the option to match after '//' and then would need to use another command to paste together what is found? Here's where I'm struggling a bit. Any help is very much appreciated.


I'm really trying to prepend the correct http or https to the matching domain between File 1 and 2.

Answer Source

Let's see:

awk 'BEGIN{OFS=FS="/"}NR==FNR{k[$3]=$0;next}$1 in k{$1=k[$1];print}'

I think it makes the job, but I don't have an awk right here to test it.

It creates a dictionary with the selected domains with the first file (NR==FNR), and for the second file it looks the domain in the created dictionary, if exists, then it replace the domain name with the full record from file 1 and then print all

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download