如何在toml配置文件中使用SED正则表达式提取JSON字段值
问题背景
我正在为zsh的starship主题创建自定义提示,该主题可通过.toml文件进行API配置。
我当前尝试使用的配置代码如下:
[custom.vtex] command = "cat $HOME/.config/configstore/vtex.json | grep account | sed -n 's/.*\:.*\"\(.*\)\".*/\1/p'" description = "My custom prompt" files = [".vtexignore"] style = "fg:red"
我使用的.json文件内容如下:
{ "env": "prod", "_nextFeedbackDate": "2021-08-17T12:43:59.194Z", "account": "example", "workspace": "workspace", "_lastUsedWorkspace": "master", "login": "email@email.com", "token": "eyJhbGciOiJFUzI1NiIsImtpZCI6IkEwRkQ4NDgzNTFG...", "_lastUsedAccount": "other-account", "apps": { ... } }
单独执行cat和grep命令返回结果为:
"account": "example",
我想要从中提取出example值展示在提示中。现在遇到的问题是不确定是不是在.toml文件中无法实现该操作,我收到了如下报错:
[ERROR] - (starship::config): Unable to parse the config file: invalid escape character in string: `:` at line 14 column 83
如果我调整转义字符的数量,报错会消失,但sed命令无任何返回结果。
编辑补充(已解决)
已补充.json文件作为示例。我在大家的帮助下成功解决了该问题,对David的回复做了调整:由于toml中的命令被双引号包裹,我仍需要对双引号做转义。最终实现方案如下,我需要同时提取account和workspace,之前没有提及是因为我原本以为可以自行解决(不过大概率有人能写出更高效更优雅的实现):
vtex_prompt.sh脚本内容:
#!/usr/bin/zsh account=$(sed -n -E '/^[[:blank:]]*\"account\"/s/^[[:blank:]]*[^[:blank:]]+[[:blank:]]\"([^\"]+)\",$/\1/p' $HOME/.config/configstore/vtex.json) workspace=$(sed -n -E '/^[[:blank:]]*\"workspace\"/s/^[[:blank:]]*[^[:blank:]]+[[:blank:]]\"([^\"]+)\",$/\1/p' $HOME/.config/configstore/vtex.json) echo "$account/$workspace"
starship.toml对应配置:
[custom.vtex] command = "zsh ~/vtex_prompt.sh" description = "VTEX Prompt" files = [".vtexignore"]
内容的提问来源于stack exchange,提问作者chemedev
相关产品推荐
相关产品推荐

