5

How can I do bash style string manipulations in Fish shell?

Specifically, in bash

read branch < ".git/HEAD"
branch=${branch#ref: refs/heads/}

will put the branch name in $branch variable.

How can I do the same in fish shell?

I glanced over documentation of fish but didn't find anything.

blackwing
  • 631

2 Answers2

6

The fish shell now has a string builtin command.

To use string instead of sed in your case:

set branch (string replace 'ref: refs/heads/' '' <.git/HEAD)

It can operate on given arguments, or on standard input.

There's lots more that string can do. From the string command documentation:

Synopsis

string length [(-q | --quiet)] [STRING...]
string sub [(-s | --start) START] [(-l | --length) LENGTH] [(-q | --quiet)]
           [STRING...]
string split [(-m | --max) MAX] [(-r | --right)] [(-q | --quiet)] SEP
             [STRING...]
string join [(-q | --quiet)] SEP [STRING...]
string trim [(-l | --left)] [(-r | --right)] [(-c | --chars CHARS)]
            [(-q | --quiet)] [STRING...]
string escape [(-n | --no-quoted)] [STRING...]
string match [(-a | --all)] [(-i | --ignore-case)] [(-r | --regex)]
             [(-n | --index)] [(-q | --quiet)] [(-v | --invert)] PATTERN [STRING...]
string replace [(-a | --all)] [(-i | --ignore-case)] [(-r | --regex)]
               [(-q | --quiet)] PATTERN REPLACEMENT [STRING...]
MattH
  • 554
3

fish is all about minimalism: if there's a common utility that does the job easily, it's not in fish. So, as you say, with sed:

set branch (sed 's#^ref: refs/heads/##' .git/HEAD)
glenn jackman
  • 27,524