从文件中读取多个字符串作为不同的变量. [英] Read multiple strings from a file as a different variables.

查看:98
本文介绍了从文件中读取多个字符串作为不同的变量.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

file.conf:

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

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.

推荐答案

对于有效的unix变量名称,您必须有一种忽略输入无效行的方法. Unix变量遵循以下规则:

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:

以下划线或字母开头,后跟0个或多个字母数字或下划线

start with underscore or an alphabet followed by 0 or more alphanumeric or underscore

使用此规则,您可以在BASH中使用此脚本:

Using this rule you can use this script in BASH:

while read k v; do
   [[ $k =~ ^[_[:alpha:]][[:alnum:]_]*$ ]] && declare $k="$v"
done < conf.file

这将忽略所有空行或以#或/usr/bin等开头的行.

This will ignore all the blank lines or lines starting with # or /usr/bin etc.

在ksh中尝试以下操作:

In ksh try this:

while read k v; do
   [[ $k =~ ^[_[:alpha:]][[:alnum:]_]*$ ]] && eval $k="$v"
done < conf.file

这篇关于从文件中读取多个字符串作为不同的变量.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆