Édouard Lopez
Édouard Lopez

Reputation: 43421

How to extract substring in Fish shell?

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?

Upvotes: 12

Views: 6134

Answers (3)

Suuuehgi
Suuuehgi

Reputation: 5010

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

Upvotes: 2

faho
faho

Reputation: 15984

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.

Upvotes: 17

Édouard Lopez
Édouard Lopez

Reputation: 43421

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

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

America

Upvotes: 3

Related Questions