Analice su configuración en un formato inequívoco, luego léala en una matriz asociativa en una versión reciente debash
:
awk '/^\[/ { app=substr($0,2,length-2) } /=/ { print app "." $0 }' file.conf
Esto encuentra todos los encabezados de sección y establece la variable awk
app
en el contenido de estos. Luego antepone cada línea siguiente con ese valor seguido de un punto.
Esto crearía una salida como
APP1.name=Application1
APP1.StatusScript=/home/status_APP1.sh
APP1.startScript=/home/start_APP1.sh
APP1.stopScript=/home/stop_APP1.sh
APP1.restartScript=/home/restart.APP1.sh
APP2.name=Application2
APP2.StatusScript=/home/status_APP2.sh
APP2.startScript=/home/start_APP2.sh
APP2.stopScript=/home/stop_APP2.sh
APP2.restartScript=/home/restart.APP2.sh
APP2.logdir=/log/APP2/
Si su APP2
careciera de una subsección name
, la línea APP2.name
no aparecería.
Luego lea esto en una matriz asociativa enbash
:
declare -A conf
while IFS='=' read -r key value; do
conf[$key]="$value"
done < <(awk '/^\[/ { app=substr($0,2,length-2) } /=/ { print app "." $0 }' file.conf)
Ahora puede consultar la variable conf
para su configuración:
printf 'The stopScript for APPN is "%s"\n' "${conf[APPN.stopScript]}"
Esto devolverá
The stopScript for APPN is "/home/stop_APPN.sh"
Consultar un valor no -existente generará una cadena vacía.
El comando awk
también podría ser reemplazado por el siguiente comando sed
:
sed -n \
-e '/^\[/{s/[][]//g;h;}' \
-e '/=/{H;g;s/\n/./;p;s/\..*//;h;}' file.conf
Ampliado y anotado:
/^\[/{ # handle section headers
s/[][]//g; # remove [ and ]
h; # put into the hold-space
}
/=/{ # handle settings
H; # append the line to the hold-space with newline as delimiter
g; # get the hold-space
s/\n/./; # replace the newline with a dot
p; # output
s/\..*//; # remove everything after the dot
h; # put back into the hold-space
}