bash 解析逗号分隔的“key: value”字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18484189/
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-09-18 06:24:47  来源:igfitidea点击:

Parsing a comma-separated "key: value" string

bash

提问by ChronoTrigger

I have a text file with several blocks with several lines that may look like this:

我有一个包含多个块的文本文件,其中几行可能如下所示:

{ key1: value, key2: value,
  key3: value,
  key4: value, key5: value }

{ key1: value, key2: value, key3: value,
  key4: value, key5: value }

Given a key, how can I get all the corresponding values? Note that neither the key names nor the values have a fixed length, blocks start and finish with braces and pairs are separated by commas.

给定 a key,我怎样才能获得所有相应的值?请注意,键名和值都没有固定长度,块以大括号开始和结束,对用逗号分隔。

My first try was with grepand cut, but I couldn't get all the keys. I guess that this should be easy with sedor awk, but their syntax confuses me a lot.

我的第一次尝试是使用grepand cut,但我无法获得所有密钥。我想这应该很容易使用sedor awk,但它们的语法让我很困惑。

回答by konsolebox

First solution with grep:

使用 grep 的第一个解决方案:

grep -o 'key5: [^, }]*' file

Shows someting like:

显示类似:

key5: value
key5: value

To remove the keys:

要删除密钥:

grep -o 'key5: [^, }]*' file | sed 's/^.*: //'

value
value

回答by Bentoy13

Using sedand grep:

使用sedgrep

sed 's|[{},]|\n|g' your-file.txt | grep -Po '(?<=key1:).*$' 

sedreformats the file to have only one pair key-value on each line; then use grepwith lookbehind to extract only values correpsonding to a specified key.

sed将文件重新格式化为每行只有一对键值;然后grep与lookbehind一起使用以仅提取与指定键对应的值。

回答by user000001

This only works if the key and value are on the same line, and if the key is not contained in any value, if values and keys do not contain spaces, commas, or colons:

这只适用于键和值在同一行,并且键不包含在任何值中,如果值和键不包含空格、逗号或冒号:

awk -F'[, :]+' '{for (i=1;i<NF;i++) if ($i=="key3") print $(i+1)}' file

or if you want to the key from a variable

或者如果您想从变量中获取密钥

awk -F'[, :]+' -v key="$key" '{for (i=1;i<NF;i++) if ($i==key) print $(i+1)}' file