这可以使用 Homebrew 的 JSON API 以及一些 jq 魔术 (brew install jq)。
1- 假设您的 .app 文件名都不包含换行符(不太可能),您可以使用 a command combining ls and jq 将列表作为 JSON 数组获取。但是,由于我们将使用该列表作为查找,因此最好创建一个对象:
ls /Applications | \grep '\.app$' | jq -Rsc 'split("\n")[:-1]|map({(.):1})|add'
这会创建一个对象,其中每个应用程序作为键,1 作为值(值在这里不重要)。它输出如下内容:
{"1Password 7.app":1,"Amphetamine.app":1, "Firefox.app":1, …}
2- 您可以使用brew search --casks 列出所有 3,500 多个可安装的木桶。为了获得描述一个或多个木桶的 JSON,包括他们安装的 .app,您可以使用 brew cask info --json=v1 <cask> …。
结合这两者,我们可以得到一个巨大的 JSON 描述所有可安装的木桶:
brew search --casks | xargs brew cask info --json=v1 > allcasks.json
此命令在我的机器上大约需要 10 秒,因此将其保存在文件中是个好主意。
3- 我们现在可以过滤此列表以仅从之前的列表中提取安装 .apps 的木桶:
cat allcasks.json | jq -r --argjson list '{…the list…}' '.[]|(.artifacts|map(.[]?|select(type=="string")|select(in($list)))|first) as $app|select($app)|"\(.token): \($app)"'
将{…the list…} 替换为我们之前创建的对象。
这会打印如下内容:
1password: 1Password 7.app
firefox: Firefox.app
google-chrome: Google Chrome.app
…
如果您喜欢冒险,这里有一个可以同时执行所有这些命令的单行代码:
brew search --casks|xargs brew cask info --json=v1|jq -r --argjson l "$(ls /Applications|\grep '\.app$'|jq -Rsc 'split("\n")[:-1]|map({(.):1})|add')" '.[]|(.artifacts|map(.[]?|select(type=="string")|select(in($l)))|first) as $a|select($a)|"\(.token): \($a)"'
jq 命令分解:
.[] # flatten the list
| # then for each element:
( # take its artifacts
.artifacts
# then for each one of them
| map(
# take only arrays
.[]?
# select their string elements
| select(type=="string")
# that are also in the list
| select(in($list)
)
)
# take the first matching artifact
| first)
# and store it in $app
as $app
# then take only the elements with a non-empty $app
| select($app)
# and print their name (.token) and the app ($app)
|"\(.token): \($app)"