问题
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.
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?
回答1:
Try 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
Gives output
artist:The Black Keys
title:Give Your Heart Away
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.
I hope this helps.
回答2:
The following works regardless what order 'title' or 'artist' come in. The only restriction is that after it sees :title
, the next line containing string
must be the title string; it doesn't matter how far away that line is though. Likewise for the artist
awk '
/:artist/{a=1;next}
/:title/{t=1;next}
a && /string/{
sub(/^.*string /,"")
artist=$0
a=0; next
}
t && /string/{
sub(/^.*string /,"")
title=$0
t=0;next
}
END{
printf("artist:%s\n title:%s\n", artist,title)
}'
Output
artist:"The Black Keys"
title:"Give Your Heart Away"
来源:https://stackoverflow.com/questions/9058791/parse-a-variant-array-using-command-line-utils-in-bash