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

Edw*_*ans 14 linux bash

我有一个文件,我需要使用shell脚本按键查找值.该文件看起来像:

HereIsAKey This is the value
Run Code Online (Sandbox Code Playgroud)

我该怎么做:

MyVar=Get HereIsAKey
Run Code Online (Sandbox Code Playgroud)

然后MyVar应该等于"这就是价值".密钥没有空格,值应该是密钥后面的空格.

Ken*_*ent 21

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

myVar=$(grep -Po "(?<=^HereIsAKey ).*" file)
Run Code Online (Sandbox Code Playgroud)


Rog*_*mbe 8

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

VAR=$(grep "^$KEY " file | cut -d' ' -f2-)
Run Code Online (Sandbox Code Playgroud)


Dan*_*der 6

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

#!/bin/bash
cat file | while read key value; do
  echo $key
  echo $value
done
Run Code Online (Sandbox Code Playgroud)

此解决方案的问题:变量仅在循环内有效.因此,不要尝试$key=$value在循环后使用它.

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

exec 3<file
while read -u3 key value; do
  eval "$key='$value'"
done
exec 3<&-
echo "$keyInFile1"
echo "$anotherKey"
Run Code Online (Sandbox Code Playgroud)


Wil*_*ell 5

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

my_var=$( awk '/^HereIsAKey/ { $1=""; print $0; exit}' value-file )
Run Code Online (Sandbox Code Playgroud)

如果文件已排序,您可以使用以下命令更快地查找

my_var=$( look HereIsAkey value-file | cut -d ' ' -f 2- )
Run Code Online (Sandbox Code Playgroud)