12

I got the following variable:

set location "America/New_York"

and want to display only the part before the / (slash) using fish shell syntax.

Expected result

America

Bash equivalent

Using bash, I was simply using a parameter expansion:

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

Question

How do I do that in a fish-way?

Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178

3 Answers3

17

Since fish 2.3.0, there's a builtin called string that has several subcommands including replace, so you'll be able to do

string replace -r "/.*" "" -- $location

or

set location (string split "/" -- $location)[1]

See http://fishshell.com/docs/current/commands.html#string.

Alternatively, external tools like cut, sed or awk all work as well.

faho
  • 14,470
  • 2
  • 37
  • 47
  • What if we care about both return values? Storing them in a list works, but is there a way to store them into more specific vars straight away? E.g. `set a, b (string split / foo/bar)` – Dennis May 16 '17 at 20:59
  • maybe you could add a link to the docs, and find out/mention what's the first version that supports `string replace`? – myrdd May 21 '19 at 10:49
  • 2.3 (which was released after that answer was written, so there were no docs to link to), http://fishshell.com/docs/current/commands.html#string. – faho May 21 '19 at 16:01
3

A possible solution is to use cut but, that look hackish:

set location "America/New_York"
echo $location|cut -d '/' -f1

America

Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
  • 2
    Part of the fish philosophy is to have as small a feature set as possible. fish does not do parameter expansion like bash with `${location%%/*}`. This answer is the fish way. From the [Design document](http://fishshell.com/docs/current/design.html): "Everything that can be done in other shell languages should be possible to do in fish, though fish may rely on external commands in doing so." – glenn jackman Dec 09 '15 at 21:15
2

Use the field selector -f of string split

> string split / "America/New_York" -f1
America

and accordingly:

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

Sidenote: For the latter string involving multiple slashes, I don't know anything better than the cumbersome -r -m1 -f2:

> string split / "foo/bar/America/New_York" -r -m1 -f2
New_York
Suuuehgi
  • 4,547
  • 3
  • 27
  • 32