简体   繁体   English

使用awk解析配置文件

[英]Using awk to parse a config file

I'm trying to make an awk command which stores an entire config file as variables. 我试图做一个awk命令,它将整个配置文件存储为变量。

The config file is in the following form (keys never have spaces, but values may): 配置文件采用以下格式(键永远不能有空格,但是值可以):

key=value
key2=value two

And my awk command is: 我的awk命令是:

$(awk -F= '{printf "declare %s=\"%s\"\n", $1, $2}' $file)

Running this without the outer subshell $(...) results in the exact commands that I want being printed, so my question is less about awk, and more about how I can run the output of awk as commands. 在没有外部子外壳$(...)情况下运行此命令,将得到我想要打印的确切命令,因此我的问题不是关于awk,而是关于如何将awk的输出作为命令运行。

The command evaluates to: 该命令的计算结果为:

declare 'key="value"'

which is somewhat of a problem, since then the double quotes are stored with the value. 这有点问题,因为然后双引号与值一起存储。 Even worse is when a space is introduced, which results in: 更糟糕的是,当引入空格时,会导致:

declare 'key2="value' two"

Of course, I cannot remove the quotes or the multi-word values cause problems. 当然,我不能删除引号,否则多字值会引起问题。

I've tried most every solution I could find, such as set -f , eval , and system() . 我已经尝试了我能找到的大多数解决方案,例如set -fevalsystem()

You don't need to use Awk for this but the do this with built-ins available. 您不需要为此使用Awk ,但是可以使用内置的插件来执行此操作。 Read the config file properly using input redirection 使用输入重定向正确读取配置文件

#!/bin/bash

while IFS== read -r k v; do
    declare "$k"="$v"
done < config_file

and source the file as 并将文件作为

$ source script.sh
$ echo "$key"
value
$ echo "$key2"
value two

If source is not available explicitly, POSIX -ly way of doing it would be to do just 如果没有明确提供source ,那么POSIX方法就是

. ./script.sh

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

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