开发者

String manipulation in fish shell

开发者 https://www.devze.com 2023-02-07 05:00 出处:网络
i wish to write a fish shell script to automatically initialize JAVA_HOME to current configured java-alternative.

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 (up开发者_JAVA百科date-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


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...]


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')))


Instead of sed, u could make use of expr with a regexp, for example:

$ set a /path/to/some/folder/file.extension

the command:

$ expr "//$a" : '.*/\([^.]*\)\..*$'
file

extract the file basename without extension.

See man expr


Fish shell:

~> set JAVA_HOME (readlink -f /usr/bin/javac | sed "s:/bin/javac::")
~> echo $JAVA_HOME

Output (example):

/usr/lib/jvm/java-8-openjdk-amd64

Also u can add to ~/.config/fish/config.fish this line:

set JAVA_HOME (readlink -f /usr/bin/javac | sed "s:/bin/javac::")

WBR

0

精彩评论

暂无评论...
验证码 换一张
取 消