简体   繁体   中英

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.

$ 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=abcd that needs to be replaced

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

And use sed -i to update my.cnf

没有削减,并且ip变量不会污染。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM