Modify the configuration file of kv mode through sed command under Linux
Sed is a character stream-oriented editor under unix, namely stream editor, which is line-oriented and processed in units of behavior. At the same time, sed is non-interactive, and once executed, the entire file will be processed.
Most of the daily backend service configuration files exist in the form of key-value, such as ini files, toml files or some custom configuration files. When we need to write automated scripts to change the configuration files in some cases, we can modify them quickly by regular matching through the sed command of shell, which is very simple and fast, and reduces the complexity of writing many "high-level languages". Two common configuration changes and command reference examples are listed below:
Profile test.conf for testing
$cat test.conf max.connections = 100test.log_path = "/ tmp/test.log" fsync=on
Value in quotation marks
#! / bin/bashCONF=test.confset_key_value () {local key=$ {1} local value=$ {2} if [- n $value]; then # echo $value local current=$ (sed-n-e "s / ^\ ($key='\)\ ([^'] *\)\ (. *\) $/\ 2echo p" $CONF) # value with single quotation marks if [- n $current] Then echo "setting $CONF: $key = $value" value= "$(echo" ${value} "| sed's | [&] |\ & | g')" sed-I "s | ^ [#] * [] ${key}\ ([] *\) = .* | ${key} ='${value}'|" ${CONF} fi fi} set_key_value "max.connections"1024" set_key_value "test.log_path" / data/logs/test.log "
The way values are not in quotation marks
CONF=test.confset_key_value () {local key=$ {1} local value=$ {2} if [- n $value]; then # echo $value local current=$ (sed-n-e "s / ^\ ($key=\)\ ([^'] *\)\ (. *\) $/\ 2echo p" $CONF) # value without single quotation marks if [- n $current] Then echo "setting $CONF: $key = $value" value= "$(echo" ${value} "| sed's | [&] |\ & | g')" sed-I "s | ^ [#] * [] ${key}\ ([] *\) = .* | ${key} = ${value} |" ${CONF} fi fi} set_key_value "fsync"off"
Summary
The above is the editor introduced to you under the Linux through the sed command to modify the kv configuration file, I hope to help you, if you have any questions, please leave me a message, the editor will reply to you in time. Thank you very much for your support to the website!