How to extract substring in Fish shell?
Asked Answered
L

3

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?

Lumumba answered 9/12, 2015 at 20:16 Comment(0)
D
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.

Deangelis answered 9/12, 2015 at 21:14 Comment(3)
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)Fennel
maybe you could add a link to the docs, and find out/mention what's the first version that supports string replace?Frontward
2.3 (which was released after that answer was written, so there were no docs to link to), fishshell.com/docs/current/commands.html#string.Deangelis
L
3

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

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

America

Lumumba answered 9/12, 2015 at 20:18 Comment(1)
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: "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."Potemkin
H
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
Hoist answered 9/6, 2021 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.