问题
In continuation of How to read multiple strings in a file as a different variables :-
file.conf:
####
#xyz
key name
/usr/bin/ /text/abc/
value pswd
Now I want write a script to having two variable like above
script.sh
key="name" #key as variable
value="pswd" #value as variable
/usr/bin/=/text/abc/
Please refer to above mentioned link for more info.
回答1:
You have to have a way to ignore the lines with invalid entry for a valid unix variable name. A unix variable follows this rule:
start with underscore or an alphabet followed by 0 or more alphanumeric or underscore
Using this rule you can use this script in BASH:
while read k v; do
[[ $k =~ ^[_[:alpha:]][[:alnum:]_]*$ ]] && declare $k="$v"
done < conf.file
This will ignore all the blank lines or lines starting with # or /usr/bin etc.
In ksh try this:
while read k v; do
[[ $k =~ ^[_[:alpha:]][[:alnum:]_]*$ ]] && eval $k="$v"
done < conf.file
来源:https://stackoverflow.com/questions/33595180/read-multiple-strings-from-a-file-as-a-different-variables