在bash中使用命令行工具解析变量数组 [英] Parse a variant array using command line utils in bash
问题描述
要获取正在Spotify中播放的当前歌曲(使用 DBus ),我使用以下命令:
To get the current song being played in spotify (using DBus), I use the following command:
dbus-send --print-reply --session --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.freedesktop.DBus.Properties.Get string:'org.mpris.MediaPlayer2.Player' string:'Metadata'
现在,以下命令的输出如下:(为清楚起见,将其删除)
Now, the output of the command below is like: (stripped down for clarity)
variant array [
dict entry(
string "xesam:artist"
variant array [
string "The Black Keys"
]
)
dict entry(
string "xesam:title"
variant string "Give Your Heart Away"
)
]
输出有点长&我想从中解析特定的值,例如标题,艺术家等。
The output is a bit long & I want to parse specific values from it like title, artist etc.
谷歌搜索表示变体是组件对象模型中使用的一种流行数据类型,因此与使用sed / awk来获取值相比,我得到了一种更好的方式。那么,我该怎么做呢?
Googling said that variant a popular datatype used in Component Object Model so I get there is a better way than using sed/awk to get the values. So, how do I go about doing this?
推荐答案
尝试一下
awk '
/string *"xesam:artist/{
while (1) {
getline line
if (line ~ /string "/){
sub(/.*string "/, "artist:", line)
sub(/".*$/, "", line)
print line
break
}
}
}
/string *"xesam:title/{
while (1) {
getline line
if (line ~ /string "/){
sub(/.*string "/, "title:", line)
sub(/".*$/, "", line)
print line
break
}
}
}
' variantArraySample.txt
礼物输出
artist:The Black Keys
title:Give Your Heart Away
这假设输入之间始终至少存在1行差异,即
This assumes that there will always be at least 1 line difference between the input, i.e.
string "xesam:title"
variant string "Give Your Heart Away"
也就是说,如果您的数据全部汇总
That is to say, if your data is all rolled up into one line, then it will require further logic, so
string "xesam:title" variant string "Give Your Heart Away"
(例如),将需要更改上述脚本。
(for example), would require changes to the above script.
如果需要帮助,请进一步格式化输出格式。
Let me know if you need help formatting the output further for your need.
我希望这会有所帮助。
这篇关于在bash中使用命令行工具解析变量数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!