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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15703822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:01:55  来源:igfitidea点击:

Easiest way to get only part of a string in bash

bash

提问by Alfred

I like to listen to sky.fm and I use curl to query media information

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

What I use right now is:

我现在使用的是:

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

This returns:

这将返回:

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

What I would like to have is:

我想要的是:

Cody Simpson - On My Mind

Maybe even better, put the artist and title in separate variables.

也许更好,将艺术家和标题放在不同的变量中。

artist: Cody Simpson
title: On My mind

Solution

解决方案

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

采纳答案by ktm5124

You can do this using cut.

您可以使用 cut 来做到这一点。

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

The cut command helps you select fields. The fields are defined by a delimiter, in this case ':'. The -doption specifies the delimiter, the -foption specifies the fields we want to select.

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

The sed part is simply to remove the quotes.

sed 部分只是删除引号。

回答by Chris Seymour

A simpler approach if you have GNU grep:

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

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

Where curl ...is replaced by your actual curlcommand.

Wherecurl ...由您的实际curl命令替换。

Edit:

编辑:

I'd go with awkfor your second request:

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

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

To store in shell variables:

要存储在 shell 变量中:

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

echo "$artist"
Cody Simpson

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

echo "$title"
On My Mind

回答by eminor

with sed:

与 sed:

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

with grep, cut and tr:

使用 grep、cut 和 tr:

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

with awk:

使用 awk:

curl -s 'http://127.0.0.1:8080/requests/status.json' | \
        awk -F':' '/now_playing/ {gsub(/"/,""); print  }'