Read multiple strings from a file as a different variables.

筅森魡賤 提交于 2019-12-13 05:18:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!