4

喜欢听sky.fm,使用curl查询媒体信息

我现在使用的是:

curl -s curl http://127.0.0.1:8080/requests/status.json | grep now_playing

这将返回:

"now_playing":"Cody Simpson - On My Mind"

我想要的是:

Cody Simpson - On My Mind

也许更好的是,将艺术家和标题放在单独的变量中。

artist: Cody Simpson
title: On My mind

解决方案

#!/bin/bash
a=`curl -s http://127.0.0.1:8080/requests/status.json | grep -Po '(?<=now_playing":")[^"]+'`
artist=$(echo $a | awk -F' - ' '{print $1}')
title=$(echo $a | awk -F' - ' '{print $2}')
echo $artist
echo $title
4

3 回答 3

4

您可以使用剪切来执行此操作。

curl -s http://127.0.0.1:8080/requests/status.json | \
   grep 'now_playing' | cut -d : -f 2 | sed 's/"//g'

剪切命令可帮助您选择字段。字段由分隔符定义,在本例中为':'-d选项指定分隔符,选项-f指定我们要选择的字段。

sed 部分只是删除引号。

于 2013-03-29T13:06:56.197 回答
2

如果您有一个更简单的方法GNU grep

curl ... | grep -Po '(?<=now_playing":")[^"]+'
Cody Simpson - On My Mind

Wherecurl ...被您的实际curl命令所取代。

编辑:

我会同意awk你的第二个要求:

curl ... | awk -F'"' '{split($4,a," - ");print "artist:",a[1],"\ntitle:",a[2]}'
artist: Cody Simpson 
title: On My Mind

要存储在 shell 变量中:

artist=$(curl ... | awk -F'"' '{split($4,a," - ");print a[1]}')

echo "$artist"
Cody Simpson

title=$(curl ... | awk -F'"' '{split($4,a," - ");print a[2]}')

echo "$title"
On My Mind
于 2013-03-29T13:18:05.983 回答
1

使用 sed:

curl -s 'http://127.0.0.1:8080/requests/status.json' | \ 
        sed '/now_playing/s/^\"now_playing\":"\(.*\)"$/\1/'

使用 grep、cut 和 tr:

curl -s 'http://127.0.0.1:8080/requests/status.json' | \ 
        grep now_playing | cut -d':' -f2 | tr -d '"'

使用 awk:

curl -s 'http://127.0.0.1:8080/requests/status.json' | \
        awk -F':' '/now_playing/ {gsub(/"/,""); print $2 }'
于 2013-03-29T13:43:11.083 回答