Sed: Find and Replace The Whole Line [ Regex ]

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

ADVERTISEMENTS

acl verizonfios src 1.2.3.4

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 4.5.6.7

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

Tutorial details
DifficultyEasy (rss)
Root privilegesYes
Requirementssed+ssh
TimeN/A
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 4.5.6.7/' file

In this example, replace an IP address with 202.1.2.3:

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

You can execute the sed command using ssh:

ssh root@your.server.at.cloud sed -i 's/^acl verizonfios.*/acl verizonfios src 202.1.2.3/' /etc/squid/squid.conf
ssh root@your.server.at.cloud /usr/sbin/squid -k reconfigure

Sample shell script

#!/bin/bash
# Author: nixCraft <www.cyberciti.biz> - GPL v2.x+
# -------------------------------------------------
 
## cloud server name ##
_rserver="your.server.at.cloud"
_ruser="root"
 
## Get your public IP ##
_myip="$(/bin/curl ifconfig.me)"
_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"
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
2 comments… add one
  • thameera Dec 14, 2012 @ 16:45

    All this time I was going to vi and doing :s/find/replace/g there. sed -i seems to be much easier.

  • goj Sep 11, 2015 @ 23:45

    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

    to

    host = myrpi

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.