Edit configuration file

Asked

Viewed 138 times

2

I have a configuration file with several parameters, example:

campo1=valor
campo2=valor
campo3=

I would like to assign a value to campo3 with Shell Script. I tried to do with awk but I couldn’t.

The value to be replaced will get in a variable.

  • echo "campo3=$valorDaSuaVariavel" >> seuArquivo.txt

  • This will cause the field3 to be inserted at the end of the file, I want to replace the value of what already exists.

1 answer

3


You can use awk with the option -F, which indicates which character will be used to separate the value field in 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 substitution 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, or write the values you already have.

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

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

trocaval.sh novo_valor arquivo.config

The exit will be:

campo1=valor
campo2=valor
campo3=novo_valor

If you want to play 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 as it can be overwritten and you will lose its content. It is more guaranteed to write first into a new file, and if so, 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.