简体   繁体   English

如何替换文件中的值

[英]how to replace value in a file

I am writing a script to alter the few values in file sysctl.conf in /etc directory 我正在编写一个脚本来更改/etc directory sysctl.conf文件中的几个值

If variable value is less than that then it should alter the value to below given value 如果变量值小于该值,则应将其更改为低于给定值

For example: 例如:

sysctl.conf file contains the following lines (the terms in parentheses are my own comments and are not in the actual file): sysctl.conf文件包含以下几行(括号中的术语是我自己的注释,不在实际文件中):

kernel.shmall = 5194304 (more than 4194304 so it should leave it as it is)
kernel.shmmax = 2147483648 (it is equal to 2147483648 so it should leave it as it is)
kernel.msgmni = 124 (it is less than 1024 so it should alter the value to 1024)

expecting output is 期望的输出是

kernel.shmall = 5194304 
kernel.shmmax = 2147483648
kernel.msgmni = 1024

This is my script I am preparing to replace kernel.shmall if value is less than or equal to 4194303 这是我准备替换kernel.shmall脚本,如果值小于或等于4194303

script: 脚本:

#!/bin/sh
echo `cat /etc/sysctl.conf|fgrep kernel.shmall` | while read kernel.shmall
if [ "kernel.shmall" -le 4194303 ]; then
    kernel.shmall = 4194304
fi`

You can do something like this 你可以做这样的事情

 sed -i "s|\("kernel.shmall" *= *\).*|\14194304|" /etc/sysctl.conf

And same you can use for other properties. 同样,您可以将其用于其他属性。

Also if property not exist then you can do like this 另外,如果属性不存在,那么您可以这样做

if grep -o "kernel.shmall" /etc/sysctl.conf > /dev/null
then
     oldvalue=$(grep kernel.shmall /etc/sysctl.conf | awk '{ print $3 }')

     if [ $oldvalue -lt 4194304 ]
     then
        sed -i "s|\("kernel.shmall" *= *\).*|\14194304|" /etc/sysctl.conf
     fi
else
     echo "kernel.shmall=" >> /etc/sysctl.conf
     sed -i "s|\("kernel.shmall" *= *\).*|\14194304|" /etc/sysctl.conf
fi

Perhaps a clearer way of getting the values from your file is: 从文件中获取值的更清晰的方法可能是:

value=$(grep kernel.shmall /etc/sysctl.conf | awk '{ print $3 }')

Then, to replace the value in the file: 然后,替换文件中的值:

sed -i "/kernel.shmall =/ s/$value/4194304/" /etc/sysctl.conf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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