Tag Archives: CLAVE

Change value in a textFile

By Xedrox

Hi everyone,

I need to make a script to take three parameters:

-> KEY
-> NEW_VALUE
-> FILE

The FILE is a text plane file.
The KEY is a variable to configure, for example:

Code:

KEY1 = HOLA
KEY2= HOLA
KEY3=HELLO
KEY4 =HOLA


And the NEW_VALUE is the string next to symbol “=”.

The script must change a value of a “KEY“. For example, supose i have the next file:

Code:

KEY1 = HOLA
KEY2 = HOLA
KEY3 =HELLO
KEY4 =HOLA


I execute the next comand: ./script ‘KEY2’ ‘BAZINGA’ ‘myFile.txt’

The result must be:

Code:

KEY1 = HOLA
KEY2 =BAZINGA
KEY3 =HELLO
KEY4 =HOLA


I did the next script:

Code:

CLAVE=$1
NEWVALUE=$2
ARCHIVO_DESTINO=$3

if [ ! -f $ARCHIVO_DESTINO ]
then
echo "ERROR EN CHANGE_VALUE_CONFIG, NO se encontro el archivo: $ARCHIVO_DESTINO"
exit 1
fi

awk -F= -v P1="$CLAVE" -v P2="$NEWVALUE" '$1==P1{$0=P2}1' $ARCHIVO_DESTINO > temporalConfig

rm $ARCHIVO_DESTINO
mv temporalConfig $ARCHIVO_DESTINO


The problem is: just works well, when there is not space between “KEY” and “=” and “VALUE”. For example “KEY1=HOLA”. I need to this work with the next format “KEY1 =HOLA”. How can i change my script?

Thanks!
Sorry for my english!

Source: FULL ARTICLE at The UNIX and Linux Forums