Peter
Peter

Reputation: 23

Command to replace string in one file with content of another file

The file /var/cpanel/mainip contains the main IP of my server and nothing else. The file /etc/csf/csf.blocklists contains a list of firewall blocklists, and part of the file contains a line with an example IP address 1.2.3.4

Normally when installing CSF firewall software on a new server, I will manually replace the example IP address with the server's main IP address. This is required to successfully fetch firewall blocklists from some providers. To simplify the setup process, I want a command that will replace the example IP address 1.2.3.4 with my main server IP so I don't have to manually do it.

I've tried a sed command, I guess I'm close to the correct command but not quite there yet. Please can you help?

sed -i '/1.2.3.4/ { r /etc/csf/csf.blocklists }' /var/cpanel/mainip

This code is not right because it outputs an error:

sed: -e expression #1, char 0: unmatched `{'

When successful, it should replace 1.2.3.4 with the actual server IP address.

Upvotes: 1

Views: 58

Answers (2)

souser
souser

Reputation: 6124

You only need to specify

sed -i '/1.2.3.4/r /etc/csf/csf.blocklists' /var/cpanel/mainip

In fact even the space is optional ; following will work too

sed -i '/1.2.3.4/r/etc/csf/csf.blocklists' /var/cpanel/mainip

You are simply specifying the pattern /1.2.3.4/ and a command after that
The command could be r for read, w for write, d for delete and a few others
An example of d to delete the entry would be

sed -i '/1.2.3.4/d' /var/cpanel/mainip

Upvotes: 0

Mihir Luthra
Mihir Luthra

Reputation: 6779

sed -i "s/1\.2\.3\.4/$(</var/cpanel/mainip)/"  /etc/csf/csf.blocklists

should do the job.

Upvotes: 1

Related Questions