Linux 从 shell 脚本解析文件中的键/值的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15365871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:26:34  来源:igfitidea点击:

Code for parsing a key/value in in file from shell script

linuxbash

提问by Edwin Evans

I have a file that I need to look up a value by key using a shell script. The file looks like:

我有一个文件,我需要使用 shell 脚本按键查找值。该文件如下所示:

HereIsAKey This is the value

How can I do something like:

我该怎么做:

MyVar=Get HereIsAKey

and then MyVar should equal "This is the value". The key has no whitespace and the value should be everything following whitespace after the key.

然后 MyVar 应该等于“这就是价值”。键没有空格,值应该是键后空格后面的所有内容。

采纳答案by Kent

if HereIsAKeyis unique in your file, try this with grep:

如果HereIsAKey在您的文件中是唯一的,请尝试使用 grep:

myVar=$(grep -Po "(?<=^HereIsAKey ).*" file)

回答by William Pursell

If the file is unsorted, lookups will be slow:

如果文件未排序,查找会很慢:

my_var=$( awk '/^HereIsAKey/ { =""; print 
my_var=$( look HereIsAkey value-file | cut -d ' ' -f 2- )
; exit}' value-file )

If the file is sorted, you can get a faster lookup with

如果文件已排序,则可以使用以下命令进行更快的查找

#!/bin/bash
cat file | while read key value; do
  echo $key
  echo $value
done

回答by Daniel Alder

If you only need one variable at a time, you can do something like this:

如果您一次只需要一个变量,您可以执行以下操作:

exec 3<file
while read -u3 key value; do
  eval "$key='$value'"
done
exec 3<&-
echo "$keyInFile1"
echo "$anotherKey"

The problem with this solution: The variables are only valid inside the loop. So don't try to do $key=$valueand use it after the loop.

此解决方案的问题:变量仅在循环内有效。所以不要试图$key=$value在循环之后做和使用它。

Update: Another way is I/O redirection:

更新:另一种方式是 I/O 重定向:

load_properties() {
    local aline= var= value=
    for file in config.properties; do
        [ -f $file ] || continue
        while read aline; do
            aline=${aline//\#*/}
            [[ -z $aline ]] && continue
            read var value <<<$aline
            [[ -z $var ]] && continue
            eval __property_$var=\"$value\"
            # You can remove the next line if you don't need them exported to subshells
            export __property_$var
        done <$file
    done
}

get_prop() {
    local var= key=
    eval $var=\"$__property_$key\"
}

回答by Petesh

I use a property file that is shared across multiple languages, I use a pair of functions:

我使用跨多种语言共享的属性文件,我使用了一对函数:

get () {
    while read -r key value; do
        if [ "$key" = "" ]; then
            echo "$value"
            return 0
        fi
    done
    return 1
}

load_propertiesreads from the config.propertiesfile populating a set of variables __property_...for each line in the file, get_prop then allows the setting of a variable based on loaded properties. It works for most of the cases that are needed.

load_propertiesconfig.properties文件中读取,为文件__property_...中的每一行填充一组变量,get_prop 然后允许根据加载的属性设置变量。它适用于大多数需要的情况。

Yes, I do realize there's an eval in there, which makes it unsafe for user input, but it works for what I needed it to do.

是的,我确实意识到那里有一个 eval,这使得用户输入不安全,但它适用于我需要它做的事情。

回答by chepner

VAR=$(grep "^$KEY " file | cut -d' ' -f2-)

The two return statements aren't strictly necessary, but provide nice exit codes to indicate success or failure at finding the given key. They can also help distinguish between "the key has a empty string for the value" and "the key was not found".

这两个 return 语句不是绝对必要的,但提供了很好的退出代码来指示找到给定键的成功或失败。它们还可以帮助区分“密钥具有值的空字符串”和“未找到密钥”。

回答by Roger Lipscombe

If you don't have a grep that supports Perl-compatible regular expressions, the following seems to work:

如果您没有支持与 Perl 兼容的正则表达式的 grep,以下内容似乎有效:

##代码##