在bash中获取字符串的部分内容最简单的方法

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

1
我已经添加了一个将艺术家和标题放入单独变量的方法。 - Chris Seymour
3个回答

4
您可以使用“cut”命令来执行此操作。
curl -s http://127.0.0.1:8080/requests/status.json | \
   grep 'now_playing' | cut -d : -f 2 | sed 's/"//g'

cut命令帮助您选择字段,这些字段由定界符定义,在本例中为':'。选项-d指定定界符,选项-f指定要选择的字段。

sed部分则是用于删除引号。


谢谢,这解决了我的问题 :). 10分钟后我会接受你的答案。你能否更好地解释一下cut命令? - Alfred
更明智的做法是将分隔符设置为",并获取第四个字段grep 'now_playing' | cut -d'"' -f4,这样就不需要使用sed了。更好的方法是查看我的答案,了解如何在grep中使用正向回溯,这样也不需要使用cut - Chris Seymour
@sudo_O:如果歌曲标题中有引号,那么这种方法就行不通了。例如:"now_playing":"how to say "goodbye""。但是,冒号也会影响结果。我认为,要想得到一个万无一失的命令,你需要花费更多的时间。 - ktm5124
你刚才说我们应该将分隔符设置为 ",因为这样可以省去使用 sed 的需要 :p - ktm5124
我了解,没错。要得到一个完美无缺的命令需要一些时间。 - ktm5124
显示剩余4条评论

2
如果您使用GNU grep,可以采用更简单的方法:
curl ... | grep -Po '(?<=now_playing":")[^"]+'
Cody Simpson - On My Mind

curl ...替换为您实际的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

这样我必须对一个URL执行两次curl。是否也可以将结果存储在变量中,只执行一次CURL?谢谢。 - Alfred

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 }'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接