I've been trying to write a simple bash script which I'll be using to install an application and update it's config file. I'm having hard time to have get it's config file modified. # DBHost=localhostDBName=test# DBPassword=any suggestions how I can get above modified as below?DBHost=localhostDBName=databaseDBPassword=password
Editing config file via a bash script
bash;shell script;text processing;configuration
The best way depends on whether you expect the file to be also modified by humans, how complex the file is, and whether you want your script to take precedence if it looks like someone else wants a different value. That is, if the file already contains DBPassword=swordfish, do you want to keep that, or replace it by DBPassword=password?A common way of dealing with this is to have a section of the file delimited by magic comments, and only edit the part between these comments. Here's a way to do this with awk. If the magic comments are not present, the new section is added at the end of the file. Warning: untested code.begin_marker='# BEGIN AUTOMATICALLY EDITED PART, DO NOT EDIT'end_marker='# END AUTOMATICALLY EDITED PART'new_section='DBHost=localhostDBName=databaseDBPassword=password'export begin_marker end_markerawk <file.conf >file.conf.new -v begin_marker=$begin_marker -v begin_marker=$end_marker -v new_section=$new_section '    1 {print}    $0 == begin_marker && !changed {        do {getline} while ($0 != end_marker); # discard old section content        print new_section;        print;        changed = 1;    }    END {if (!changed) {print begin_marker; print new_section; print end_marker;}}'ln -f file.conf file.conf.oldmv -f file.conf.new file.confThis approach doesn't work well if the program that reads the configuration file doesn't support multiple lines setting the same configuration item. In that case, you'll really need to remove the old ones. In this case I would advise leaving the comments untouched and adding your own settings at the end.grep -vE '^[[:blank:]]*(DBHost|DBName|DBPassword)=$' <file.conf >file.conf.newcat <<EOF >>file.conf.newDBHost=localhostDBName=databaseDBPassword=passwordEOFln -f file.conf file.conf.oldmv -f file.conf.new file.conf