ObiHill
ObiHill

Reputation: 11876

Linux command to replace text in a file with text from redirected output

I'm working on a shell script to automate some server tasks. One the major things I need to do is configuration.

I'm trying to find a quick way to extract data from one source and then replace data at another source. In a nutshell, what I'm trying to do is replace the IP address in my.cnf with the one from ifconfig. The ip address I want to change is the bind-address.

Here's an example of what I want to do:

A. Use ifconfig - to get network info (which will include the ip address).

B. With that output, use a regular expression to extract just the ip address

C. Use the IP address to replace the bind address value in my.cnf

I'm not so conversant with piping and redirecting. I'm pretty sure I might have to output to a variable, then use that variable in another command to complete the operation? And would this be easier to do with perl?

EDIT

Here's the code that did it:

ip=`ifconfig eth0 | grep "inet addr"| cut -d ":" -f2 | cut -d " " -f1` ; sed -i "s/\(bind-address[\t ]*\)=.*/\1= $ip/" /etc/mysql/my.cnf

Many thanks to Jaidev Sridhar for the direction.

Upvotes: 1

Views: 700

Answers (3)

h0tw1r3
h0tw1r3

Reputation: 6818

No cuts and the ip variable does not pollute.

ip="`ifconfig eth0 | sed 's/.*inet addr:\([0-9\.]*\).*/\1/p'`" sed -i "s/^\(bind_address\)=.*/\1=$ip/" /etc/my.cnf

Upvotes: 0

Kashyap
Kashyap

Reputation: 17441

You can use awk/cut/sed to extract the IP address out of ifconfig output.

And use sed -i to update my.cnf

Upvotes: 0

jman
jman

Reputation: 11606

$ ip=`ifconfig eth0 | grep "inet addr"| cut -d ":" -f2 | cut -d " " -f1`; sed -i "s/MYIP=.*/MYIP=$ip/g" foo.cnf

Assuming:

  • eth0 is the interface
  • You need the ipv4 address
  • Your conf file is foo.cnf and it has a line MYIP=a.b.c.d that needs to be replaced

Upvotes: 1

Related Questions