如何在Fish shell中提取子字符串?

12

我得到了以下变量:

set location "America/New_York"

想要仅显示斜杆/前面的部分,使用fish shell语法。

期望结果

America

Bash等效命令

在bash中,我只是使用了参数扩展:

location="America/New_York"
echo ${location##*/}"

问题

我该如何用fish的方式做到这一点?

3个回答

17

自fish 2.3.0版本开始,有一个名为string的内置命令,其中包括replace等多个子命令,因此您可以执行以下操作:

string replace -r "/.*" "" -- $location
或者
set location (string split "/" -- $location)[1]

请查看http://fishshell.com/docs/current/commands.html#string,或者使用外部工具如 cutsedawk


如果我们关心返回值,怎么办?将它们存储在列表中可以解决问题,但是有没有一种方法可以直接将它们存储到更具体的变量中?例如:set a, b (string split / foo/bar) - Dennis
也许您可以添加文档链接,并查找/提及支持“字符串替换”的第一个版本是哪个? - myrdd
2.3版本是在那篇答案发布之后发布的,因此没有文档可供链接,可以参考http://fishshell.com/docs/current/commands.html#string。 - faho

3
一种可能的解决方案是使用cut,但这看起来很不专业:
set location "America/New_York"
echo $location|cut -d '/' -f1

美国


2
鱼哲学的一部分是尽可能拥有最小的功能集。fish不像bash那样使用${location%%/*}进行参数扩展。这个答案是fish的方式。从设计文档中可以看到:“其他Shell语言可以做的所有事情都应该在fish中实现,尽管fish可能会依赖外部命令来完成。” - glenn jackman

2
请使用字段选择器-f来拆分字符串。
> string split / "America/New_York" -f1
America

因此:

set location (string split / "America/New_York" -f1)

顺便提一下:对于包含多个斜杠的后面那个字符串,我不知道有比冗长的-r -m1 -f2更好的方法:

> string split / "foo/bar/America/New_York" -r -m1 -f2
New_York

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