Parse a variant array using command line utils in bash

让人想犯罪 __ 提交于 2019-12-24 10:26:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!