简体   繁体   中英

Linux shell replace content in file

guys. There is a file named 'server.conf' and I want to use shell to change content from it. In line 115, there is server-bridge 192.168.50.225(ip) 255.255.0.0(mask) 192.168.10.50(begin ip) 192.168.10.90(end ip) in it. I want to change the ip , mask , begin ip and end ip . For example, I plan to change

`server-bridge 192.168.50.225 255.255.0.0  192.168.10.50 192.168.10.90` 

into

`server-bridge 192.168.10.100 255.255.0.0  192.168.10.60 192.168.10.80` 

What should I do with sed or others tools? Thanks a lot.

sed -i 's/server-bridge\\ 192.168.50.225\\ 255.255.0.0\\ \\ 192.168.10.50\\ 192.168.10.90/server-bridge\\ 192.168.10.100\\ 255.255.0.0\\ \\ 192.168.10.60\\ 192.168.10.80/' server.conf

You can also create a simple script where new values to be replaced are stored in $ip ..etc.... sed -i will do in place editing to the file.

The best tool I have used is Vi.

(sudo) vi /home/mydoc.txt will open and allow you to do any editing you need done. If you have never used Vi before, there are some great HOW-TO's and tutorials online. Here is one:

http://www.howtogeek.com/102468/a-beginners-guide-to-editing-text-files-with-vi/

But I'd encourage you to really read and experiment on test files before you change the file you are referencing, AND, PLEASE, make a backup up the file ( cp /home/mydoc.txt mydoc.txt-orig ) before you do. You can always remove the edited file that does not work, but restoring the original after extensive exiting can be a hair-pulling experience.

you can use sed to do this for example some thing like this Note:every space is escaped by \\ sed Intro

   cat server.conf | sed 's/server-bridge\ 192.168.50.225\ 255.255.0.0\ \ 192.168.10.50\ 192.168.10.90/server-bridge\ 192.168.10.100 255.255.0.0\ \ 192.168.10.60\ 192.168.10.80/' > server.conf

or you can use two files for safety like this

cat server.conf | sed 's/server-bridge\ 192.168.50.225\ 255.255.0.0\ \ 192.168.10.50\ 192.168.10.90/server-bridge\ 192.168.10.100 255.255.0.0\ \ 192.168.10.60\ 192.168.10.80/' > server.conf.bak
cat server.conf.bak > server.conf

You can use this awk:

awk -v ip='192.168.10.100' -v mask='255.255.0.0' -v bip='192.168.10.60' \
 -v eip='192.168.10.80' '/server-bridge/{$2=ip "(ip)"; $3=mask "(mask)"; $4=bip "(begin";
 $6=eip "(end"} 1' server.conf

Using sed to change all lines containing server-bridge :

sed -i -e '/^server-bridge/!b' \
    -e 'c server-bridge 192.168.10.100 255.255.0.0  192.168.10.60 192.168.10.80' input

to change th 115th line only:

sed -i -e '115!b' \
    -e 'c server-bridge 192.168.10.100 255.255.0.0  192.168.10.60 192.168.10.80' input

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