0

The .conf before :

db_chat_ip = '1'
db_chat_port = '2'
db_chat_name = '3'
db_chat_user = '4'
db_chat_pass = '5'

what I want :

db_chat_ip = 51.159.26.205
db_chat_port = 57763
db_chat_name = vimeodb
db_chat_user = vimeodb
db_chat_pass = [(W>J5aGLx

my code which work :

awk -v ip=$IP -F" " '/\db_chat_ip/{$3=ip}{print}' $CONFIG_FILE > $CONFIG_FILET && mv $CONFIG_FILET $CONFIG_FILE
awk -v port=$PORT -F" " '/\db_chat_port/{$3=port}{print}' $CONFIG_FILE > $CONFIG_FILET && mv $CONFIG_FILET $CONFIG_FILE
awk -v name=$DBNAME -F" " '/\db_chat_name/{$3=name}{print}' $CONFIG_FILE > $CONFIG_FILET && mv $CONFIG_FILET $CONFIG_FILE
awk -v name=$DBNAME -F" " '/\db_chat_user/{$3=name}{print}' $CONFIG_FILE > $CONFIG_FILET && mv $CONFIG_FILET $CONFIG_FILE
awk -v pass=$DBPASS -F" " '/\db_chat_pass/{$3=pass}{print}' $CONFIG_FILE > $CONFIG_FILET && mv $CONFIG_FILET $CONFIG_FILE

In my bash I get $IP, $PORT, $DBNAME ... and replace it in the config file .

Is there a way to make it more shorter ?

LexaGC
  • 110
  • 3
  • 13
  • Does this answer your question? [Save modifications in place with awk](https://stackoverflow.com/questions/16529716/save-modifications-in-place-with-awk) – steffen Mar 04 '21 at 13:01
  • @Quasímodo I edit my question / steffen well it use gawk as James answer – LexaGC Mar 04 '21 at 14:50

1 Answers1

1

If you are after shortness, using GNU awk you could:

$ gawk -i inplace -v db_chat_ip="'34'" '  # variables named after file keys
{
    if($1 in SYMTAB)                      # check if file key is defined as var
        $3=SYMTAB[$1]                     # change value if it is
    print                                 # output inplace
}' file

Output:

$ cat file
db_chat_ip = '34'
db_chat_port = '2'
db_chat_name = '3'
db_chat_user = '4'
db_chat_pass = '5'

Just in case of collisions (extra records in file that might interfere with builtin variables or such) you could introduce some checking:

BEGIN {
    a["db_chat_ip"]                   # state variables available for changing
    a["db_chat_port"]
    a["db_chat_name"]
    a["db_chat_user"]
    a["db_chat_pass"]
}
{
    if(($1 in a) && ($1 in SYMTAB))   # test for availability 
        $3=SYMTAB[$1]
    print
}
James Brown
  • 36,089
  • 7
  • 43
  • 59