简体   繁体   English

如何在shell脚本中解析配置文件(* .conf)?

[英]how to parse a config file (*.conf) in shell script?

I am new to shell script. 我是shell脚本的新手。 I have a file app.conf as : 我有一个app.conf文件:

[MySql]
user = root
password = root123
domain = localhost
database = db_name
port = 3306

[Logs]
level = logging.DEBUG

[Server]
port = 8080

I want to parse this file in shell script and want to extract mysql credentials from the same. 我想在shell脚本中解析这个文件,并希望从中提取mysql凭据。 How can I achieve that? 我怎样才能做到这一点?

I'd do this: 我这样做:

pw=$(awk '/^password/{print $3}' app.conf)

user=$(awk '/^user/{print $3}' app.conf)


echo $pw
root123

echo $user
root

The $() sets the variable pw to the output of the command inside. $()将变量pw设置为内部命令的输出。 The command inside looks through your app.conf file for a line starting password and then prints the 3rd field in that line. 内部命令在app.conf文件中查找行启动password ,然后在该行中打印第3个字段。

EDITED EDITED

If you are going to parse a bunch of values out of your config file, I would make a variable for the config file name: 如果要从配置文件中解析出一堆值,我会为配置文件名创建一个变量:

CONFIG=app.conf
pw=$(awk '/^password/{print $3}' "${CONFIG}")
user=$(awk '/^user/{print $3}' "${CONFIG}")

Here's how to do the two different ports... by setting a flag to 1 when you come to the right section and exiting when you find the port. 以下是如何执行两个不同的端口...当您到达右侧部分时将标志设置为1,并在找到端口时退出。

mport=$(awk '/^\[MySQL\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}")
sport=$(awk '/^\[Server\]/{f=1} f==1&&/^port/{print $3;exit}' "${CONFIG}")

Using awk: 使用awk:

awk -F ' *= *' '$1=="user"||$1=="password"{print $2}' my.cnf
root
gogslab

You will want to search for "shell ini file parser". 您将要搜索“shell ini文件解析器”。 I would start with something like this: 我会从这样的事情开始:

ini_get () {
    awk -v section="$2" -v variable="$3" '
        $0 == "[" section "]" { in_section = 1; next }
        in_section && $1 == variable {
            $1=""
            $2=""
            sub(/^[[:space:]]+/, "")
            print
            exit 
        }
        in_section && $1 == "" {
            # we are at a blank line without finding the var in the section
            print "not found" > "/dev/stderr"
            exit 1
        }
    ' "$1"
}

mysql_user=$( ini_get app.conf MySql user )

I ran in a similar problem yesterday and thought the best solution might be, if you get an associative array like "key - value" after parsing the file. 昨天我遇到了类似的问题并且认为最好的解决方案可能是,如果在解析文件后得到像“key - value”这样的关联数组。

I you like to see a running example have a look at https://github.com/philippkemmeter/set-resolution/blob/master/set-resolution . 我想看一个正在运行的例子来看看https://github.com/philippkemmeter/set-resolution/blob/master/set-resolution

Adapted to your problem, this might work: 适应您的问题,这可能有效:

function receive_assoc_declare_statement {
    awk -F '=' 'BEGIN {ORS=" "}
    { 
        gsub(/[ \t]+/, "", $1); 
        gsub(/[ \t]+/, "", $2);
        print "[" $1 "]=" $2
    }' app.conf
}

eval 'declare -A CONF=('`receive_assoc_declare_statement`')'

You then have access to for instance user via ${CONF[user]} . 然后,您可以通过${CONF[user]}访问例如用户。

The gsub is trimming keys and values, so that you can use tab etc. to format your config file. gsub正在修剪键和值,因此您可以使用制表符等格式化配置文件。

It's lacking sections, but you could add this functionality using sed to create one config array per section: 它缺少部分,但您可以使用sed添加此功能,以便为每个部分创建一个配置数组:

sed -n '/\[MySql\]/, /\[/ {p}' test.removeme | sed '1 d; $ d'

So answering your question in total, this script might work: 总的来说回答你的问题,这个脚本可能有用:

MYSQL=`sed -n '/\[MySql\]/, /\[/ {p}' app.conf | sed '1 d; $ d' | awk -F '=' 'BEGIN {ORS=" "}
{
    gsub(/[ \t]+/, "", $1); 
    gsub(/[ \t]+/, "", $2);
    print "[" $1 "]=" $2
}' `
eval 'declare -A MYSQL=('$MYSQL')'

The other sections correspondingly. 其他部分相应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM