Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String manipulation in fish shell

Tags:

fish

i wish to write a fish shell script to automatically initialize JAVA_HOME to current configured java-alternative.

In bash it would look like this (sorry for the ugly double dirname)

j=`update-alternatives --query javac | grep Value:`
JAVA_HOME=`dirname ${j#Value:}`
JAVA_HOME=`dirname $JAVA_HOME`
export JAVA_HOME

what about fish?

set j (update-alternatives --query javac | grep Value:)
set JAVA_HOME (dirname ${j#Value:}) <-- this won't work!!
set JAVA_HOME (dirname $JAVA_HOME)
set --export JAVA_HOME
like image 550
lrkwz Avatar asked Jan 29 '11 19:01

lrkwz


2 Answers

The fish shell now has a string builtin command for string manipulation. This was added in version 2.3.0 (May 2016).

E.g. in this case, we could use string replace to remove the Value: substring:

set j (update-alternatives --query javac | grep Value: | string replace 'Value: ' '')
set --export JAVA_HOME (dirname (dirname $j))

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...]
like image 198
mattbh Avatar answered Sep 20 '22 03:09

mattbh


Bash:

j=$(update-alternatives --query javac | sed -n '/Value: /s///p')
export JAVA_HOME=${j%/*/*}

Fish:

set j (update-alternatives --query javac | sed -n '/Value: /s///p')
set --export JAVA_HOME (dirname (dirname $j))

or

set --export JAVA_HOME (dirname (dirname (update-alternatives --query javac | sed -n '/Value: /s///p')))
like image 26
Dennis Williamson Avatar answered Sep 20 '22 03:09

Dennis Williamson