我正在编写一个简短的 bash 脚本,以从 curl 响应中获取 JSON 元素。
curl -H "api_key:[API_PASSWORD]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false
返回:
[{"id":0,"seq":0,"raw":"ˈbʌt(ə)n","rawType":"IPA"},{"id":0,"seq":0,"raw":"ˈbʌt(ə)n","rawType":"IPA"}]
我正在尝试提取“ˈbʌt(ə)n”元素。
虽然我不熟悉正则表达式,但我认为我应该使用以下字符串进行替换:
/.*"(.*)",/
我正在尝试运行以下命令,但它似乎不起作用:
curl -H "api_key:[API_KEY]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false | sed /.*"(.*)",\1/
我确信我做错了几件事,在搜索和阅读正则表达式和 bash 几个小时后,我别无选择。
我不需要使用 sed,我只是在寻找一种在 bash 命令行中执行此操作的快速方法,以便我可以在 mac 上的 TextExpander 脚本中实现它。
最佳答案
使用STRING : REGEXP
从json字符串中提取值:
string=$(curl -H "api_key:[API_PASSWORD]" http://api.wordnik.com/v4/word.json/button/pronunciations?sourceDictionary=macmillan&typeFormat=IPA&useCanonical=false)
raw=$(expr "$string" : '.*"raw":"\([^"]*\)"')
echo $raw
参见 man expr
:
STRING : REGEXP
anchored pattern match of REGEXP in STRING
Pattern matches return the string matched between \( and \) or null
关于regex - 如何使用 curl 和 sed 从简短的 json 查询中提取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7473951/