While writing a shell script, how do I extract all values for a particular key in a single line string which is a list of tuples? For instance, my string is:
在编写shell脚本时,如何在单个行字符串中提取特定键的所有值,这是一个元组列表?例如,我的字符串是:
[{"key1":"value1", "key2":"value2"},{"key1":"val1","key2":"val2"}]
and the output should be an array containing value1
and val1
.
输出应该是一个包含value1和val1的数组。
2 个解决方案
#1
1
Here's a fragile approach based on a whole bunch of assumptions about what your input contains based on the sample you've shown us:
根据您向我们展示的样本,基于对输入所包含内容的一系列假设,这是一种脆弱的方法:
$ awk -F'[":]+' -v k="key1" '{for (i=2;i<=NF;i+=3) if ($i==k) print $(i+1)}' file
value1
val1
#2
1
This is going to be much more fragile than using a real parser, so you will likely find that downloading jq
could be worth it in the long run, but if you want to use only grep, since you're on Ubuntu you should have GNU grep and could do the following for the string you gave:
这比使用真正的解析器要脆弱得多,所以你可能会发现从长远来看下载jq值得,但如果你只想使用grep,因为你在Ubuntu上你应该有GNU grep并且可以为您提供的字符串执行以下操作:
grep -Po 'key1":"\K[^"]+'
which uses -P
to use Perl-style regular expressions, the -o
to show only the matching part. We add the \K
in the pattern so that everything before it will not be counted as part of the match.
它使用-P来使用Perl样式的正则表达式,-o只显示匹配的部分。我们在模式中添加\ K,以便它之前的所有内容都不会被计为匹配的一部分。
So with your input I do the following:
因此,根据您的输入,我执行以下操作:
$ printf '[{"key1":"value1", "key2":"value2"},{"key1":"val1","key2":"val2"}]' | grep -Po 'key1":"\K[^"]+'
value1
val1
Compare this to jq
which actually understands JSON:
将此与实际了解JSON的jq进行比较:
jq '[ .[] | .["key1"] ]'
Output:
输出:
[
"value1",
"val1"
]
#1
1
Here's a fragile approach based on a whole bunch of assumptions about what your input contains based on the sample you've shown us:
根据您向我们展示的样本,基于对输入所包含内容的一系列假设,这是一种脆弱的方法:
$ awk -F'[":]+' -v k="key1" '{for (i=2;i<=NF;i+=3) if ($i==k) print $(i+1)}' file
value1
val1
#2
1
This is going to be much more fragile than using a real parser, so you will likely find that downloading jq
could be worth it in the long run, but if you want to use only grep, since you're on Ubuntu you should have GNU grep and could do the following for the string you gave:
这比使用真正的解析器要脆弱得多,所以你可能会发现从长远来看下载jq值得,但如果你只想使用grep,因为你在Ubuntu上你应该有GNU grep并且可以为您提供的字符串执行以下操作:
grep -Po 'key1":"\K[^"]+'
which uses -P
to use Perl-style regular expressions, the -o
to show only the matching part. We add the \K
in the pattern so that everything before it will not be counted as part of the match.
它使用-P来使用Perl样式的正则表达式,-o只显示匹配的部分。我们在模式中添加\ K,以便它之前的所有内容都不会被计为匹配的一部分。
So with your input I do the following:
因此,根据您的输入,我执行以下操作:
$ printf '[{"key1":"value1", "key2":"value2"},{"key1":"val1","key2":"val2"}]' | grep -Po 'key1":"\K[^"]+'
value1
val1
Compare this to jq
which actually understands JSON:
将此与实际了解JSON的jq进行比较:
jq '[ .[] | .["key1"] ]'
Output:
输出:
[
"value1",
"val1"
]