Sed: Find and Replace The Whole Line [ Regex ]

in Categories , , last updated December 14, 2012

I have a line as follows in squid.conf file. My sever is hosted in a cloud:

acl verizonfios src

My ISP will force an IP address change every week or two. I would like to replace them with a new IP

acl verizonfios src

How do I replace the line starting with “acl verizonfios” with new IP address using sed and ssh?

The sed syntax is as follows to match the line starting with “acl verizonfios” and replace the whole line:

sed -i 's/find/replace/' file
sed -i 's/^acl verizonfios.*/acl verizonfios src' file

In this example, replace an IP address with

sed -i 's/^acl verizonfios.*/acl verizonfios src' /etc/squid/squid.conf

You can execute the sed command using ssh:

ssh sed -i 's/^acl verizonfios.*/acl verizonfios src' /etc/squid/squid.conf
ssh /usr/sbin/squid -k reconfigure

Sample shell script

# Author: nixCraft <> - GPL v2.x+
# -------------------------------------------------
## cloud server name ##
## Get your public IP ##
_cmd1="/bin/sed -i 's/^acl verizonfios.*/acl verizonfios src ${_myip}/' /etc/squid/squid.conf"
_cmd2="/usr/sbin/squid -k reconfigure"
## connect to the remote box 
## update the proxy server 
## reload the proxy server
/bin/ssh ${_ruser}@${_rserver} "$_cmd1"
/bin/ssh ${_ruser}@${_rserver} "$_cmd2"

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Share this on (or read 2 comments/add one below):

2 comment

  1. I wanted to change the name of my raspberrypi hostname in a conf file, but the above example did not work for me (it inserted the new name at the beginning, but left the old name, too)

    Here is the command I ended up using:

    sed -i “/^host =/c\host = myrpi” inputs_test.conf

    this changed:

    host = raspberrypi


    host = myrpi

    Have a question? Post it on our forum!