====== SED - Change - Change lines in a file ====== This script will obtain the current IP address for different sites and update the /etc/hosts file with the correct IP address. It could be run through Cron to ensure that the host file keeps an updated list of IPs. ---- ===== Input file ===== Assuming /etc/hosts contains: 1.2.3.4 restrict.youtube.com 1.2.3.4 restrictmoderate.youtube.com 1.2.3.4 strict.bing.com 1.2.3.4 forcesafesearch.google.com 1.2.3.4 safe.duckduckgo.com ---- ===== Script using dig ===== #!/bin/bash update_ip_address() { file=/etc/hosts if [[ $(grep $1 $file) ]]; then IP=$(dig +noall +answer +short @8.8.8.8 $1 | \ grep -oE '((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))') sed -i "/$1/ s/.*/$IP\t$1/g" $file fi } update_ip_address restrict.youtube.com update_ip_address restrictmoderate.youtube.com update_ip_address strict.bing.com update_ip_address forcesafesearch.google.com update_ip_address safe.duckduckgo.com ---- ===== Script using nslookup ===== #!/bin/bash update_ip_address() { file=/etc/hosts if [[ $(grep $1 $file) ]]; then IP=$(nslookup -query=A $1 8.8.8.8 | grep 'Address:' | tail -1 | \ grep -oE '((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}((1?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))') sed -i "/$1/ s/.*/$IP\t$1/g" $file fi } update_ip_address restrict.youtube.com update_ip_address restrictmoderate.youtube.com update_ip_address strict.bing.com update_ip_address forcesafesearch.google.com update_ip_address safe.duckduckgo.com ---- ===== Output File ===== The original input file will be changed to this: 216.239.38.120 restrict.youtube.com 216.239.38.119 restrictmoderate.youtube.com 204.79.197.220 strict.bing.com 216.239.38.120 forcesafesearch.google.com 52.142.126.100 safe.duckduckgo.com