Append or modify keys in conf files using sed/bash one-liner -


i have modify files such sysctl.conf, , i'm familiar using sed replace existing values.

is there way append new key/value pair file if sed wasn't able replace it?

for instance, using example: modify config file using bash script

sed -c -i "s/\($target_key *= *\).*/\1$replacement_value/" $config_file 

how add $target_key = $replacement_value new line $config_file using same sed expression slight changes?

and on related topic, how can force creation of $config_file if didn't exist?

you can't in single sed call. it's simplest make 2 steps:

if grep -q "$target_key *= " $config_file;       sed -c -i "s/\($target_key *= *\).*/\1$replacement_value/" $config_file else    echo "$target_key = $replacement_value" >>$config_file fi 

there few things should make above more robust, however:

  1. your regular expression not anchored, means trying set 'port' find/change 'support', etc.

  2. it won't match if config file might have tabs spaces

  3. it fails if replacement value has slashes in it.

  4. you should quote parameter expansions $config_file, in case file path contains spaces or shell metacharacters.

  5. it's safe in instance, potentially confusing use single backslashes in double-quoted string when want literal backslash. shell leaves them alone when doesn't recognize comes after special sequence, clearer if doubled them.

  6. what -c on version of sed? neither linux nor mac versions support such option.

so way (the ^i's represent literal tab characters, , ^a's literal control-a characters, entered example typing control-v first on command line):

if grep -q "^[ ^i]*$target_key[ ^i]*=" "$config_file";    sed -i -e "s^a^\\([ ^i]*$target_key[ ^i]*=[ ^i]*\\).*$^a\\1$replacement_value^a" "$config_file" else    echo "$target_key = $replacement_value" >> "$config_file" fi 

Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -