Change value in a textFile

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:

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:

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

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

The result must be:

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

I did the next script:

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!

awk -F' *= *' ....

Watch out in your awk script - I assume you don't want {$0=P2} but {$2=P2} .

If you really want to keep your spacing, try sth like sub(/[^ ]*/, P2, $2) in the action part. If your key contains spaces, the regex will be a bit more difficult to define.

Try this code:

awk -F= -v P1="$CLAVE" -v P2="$NEWVALUE" '{F1=$1; gsub(" ","",F1); if(P1==F1) $2=P2;}1' OFS== myFile.txt

Excellent! Works bipinajith!. I have to take time to read this "awk" :b: