2

I have no problem adding config files to a given script, but automatically updating them is another matter. In this instance I'm providing a few variables to a script, and I'd like the script to be able to change the values provided by the config file. Is there a standard way to change the value of a variable in a running script, and then update the config file accordingly? My current approach is sed-ing for the line containing the variable and changing its contents, but I feel like there must be a better way.

For example, imagine a program that generates some arbitrary text file:
Line in config file, defining a variable available to the program:

EXIT_ON_GEN="true" //exit on successful generation of text file if true

The user selects a menu option that indicates they would like to stay in the program instead, because they like generating arbitrary text so much. It would be easy to simply set it to false for the current instance of the program, but what's the best way to change the config file itself, so the user doesn't have to go back and change the settings each time they run it?

  • 2
    It would help if you provided some brief and specific examples showing what you want. – John1024 Mar 18 '15 at 19:47
  • 1
    ed, sed and perl are all very good at editing files in-place. – glenn jackman Mar 18 '15 at 20:11
  • @John1024 I added a fairly brief and specific example, though I wasn't sure if you meant specific in relation to my intent or the actual purpose of the script. Also, I meant to write that I used sed to handle the find and replace, but I use grep far more often and absent-mindedly put that in by mistake. – user67459 Mar 19 '15 at 1:02
  • @user67459 What makes you unhappy with the sed approach? – John1024 Mar 19 '15 at 1:07
  • 1
    @user67459 That would be nice. I think the problem is that unix/linux never settled on a single config file format. Consequently, there is no general tool to handle them. – John1024 Mar 19 '15 at 2:57
2

Using sed

Starting with this file:

$ cat >file
EXIT_ON_GEN="true" //exit on successful generation of text file if true

One method for changing true to false (and displaying the new version on the terminal) would use sed:

$ sed 's/^EXIT_ON_GEN=[^[:space:]]*/EXIT_ON_GEN="false"/' file
EXIT_ON_GEN="false" //exit on successful generation of text file if true

To instead make the change to the file in place, use the -i option:

$ sed -i 's/^EXIT_ON_GEN=[^[:space:]]*/EXIT_ON_GEN="false"/' file

Using awk

$ awk -F'"' -v OFS='"' '/^EXIT_ON_GEN/{$2="false"} 1' file
EXIT_ON_GEN="false" //exit on successful generation of text file if true

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.