Edit configuration file

2

I have a configuration file with several parameters, for example:

campo1=valor
campo2=valor
campo3=

I would like to assign a value to campo3 with Shell Script. I tried to awk but could not.

The value to be replaced will have a variable.

    
asked by anonymous 17.08.2018 / 20:16

1 answer

3

You can use awk with the -F option, which indicates which character will be used to separate the field from the value on each line. In this case, I will use = , to separate the field name from its value.

Then just compare the field name and make the replacement according to what you need. The script would look like this:

#!/bin/bash
valor=$1
arquivo=$2
awk -F'=' '{if ($1 == "campo3") { print $1 "=" ENVIRON["valor"] } else { print $1 "=" $2}}' $arquivo

That is, if the field name is campo3 , write the new value, otherwise it writes the values that already have.

The script receives two parameters: the value to be placed in campo3 and the name of the file to be read. I assign the script parameters to variables with clearer names, so they are not to be confused with the $1 and $2 fields of awk (in this case, within awk , $1 is the name of the field and $2 is its value).

For example, if the script name is trocaval.sh , just run:

trocaval.sh novo_valor arquivo.config

The output will be:

campo1=valor
campo2=valor
campo3=novo_valor

If you want to throw the output to a new file, use > to redirect the output:

trocaval.sh novo_valor arquivo.config > novo_arquivo.config

I do not recommend redirecting the output to the same file because it can be overwritten and you will lose its contents. It is more guaranteed to write first in a new file, and if necessary, rename it:

mv novo_arquivo.config arquivo.config

If you want, you can put all this inside the script too:

#!/bin/bash
valor=$1
arquivo=$2

# joga a saída do awk em um novo arquivo
awk .... > novo_arquivo
# renomeia o novo_arquivo para o nome do arquivo original
mv novo_arquivo $arquivo
    
17.08.2018 / 21:00