Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text after variable expansion - Fish

Tags:

shell

fish

I want to add text after variable expansion, but fish thinks I'm referring to a different variable name e.g.

$ set dessert "cake"
$ echo $dessert
cake
$ echo "I want 7 $desserts"
I want 7 
$ cat ./menu.txt | sed "s/$desserts/cookie/g"
sed: first RE may not be empty
like image 731
user14492 Avatar asked Sep 02 '26 12:09

user14492


1 Answers

Looks like you want to put curly brackets around your vaiable, like "{$dessert}s." Example:

> set xyz blarch
> echo $xyz
blarch
> echo ${xyz}
Variables cannot be bracketed. In fish, please use {$xyz}.
fish: echo ${xyz}
            ^
> echo {$xyz}
blarch
> echo i like {$xyz}s
i like blarchs
> 

edit 2: Hmm... bonus fish expansion r.e. @glenn jackman's example: Arranged this way to see output differences more easily:

        example fish command                     ::    result
-------------------------------------------------::------------------------
> set foo bar; echo shakespere was a {$foo}      :: shakespere was a bar
> set foo bar; echo shakespere was a {$foo}d     :: shakespere was a bard
> set foo bar; echo "shakespere was a {$foo}d"   :: shakespere was a {bar}d
> set foo bar; echo "shakespere was a {"$foo"}d" :: shakespere was a {bar}d
> set foo bar; echo "shakespere was a "{$foo}"d" :: shakespere was a bard
> set foo bar; echo "shakespere was a "$foo"d"   :: shakespere was a bard
> 

Seems like the last one is most efficient.

edit: I wanted to call out that Fish is a bit different w/var expansion than on other shells, like bash. Note the behavior, {$xyz} doesn't fail, but it doesn't work the same way as Fish... instead the { }'s are treated a literals there and it yields "{moreblarch}" like this:

bash example:

$ export xyz=moreblarch
$ echo $xyz
moreblarch
$ echo {$xyz}
{moreblarch}
$ echo ${xyz}
moreblarch
$ echo who doesnt like ${xyz}s?
who doesnt like moreblarchs?
$ 

edit 3: fish permutations as per @glennjackman's array comment This is not what I would have expected :-) The "echo -e" will interpret \n as a newline, makes it easier to see the output. Note that the permutations have a space inserted between them (which is why #2 - #27 have a leading space).

> set a A B C; set b 1 2 3; set c x y z; echo -e ":a="$a" b="$b" c="$c":\n"
:a=A b=1 c=x:
 :a=B b=1 c=x:
 :a=C b=1 c=x:
 :a=A b=2 c=x:
 :a=B b=2 c=x:
 :a=C b=2 c=x:
 :a=A b=3 c=x:
 :a=B b=3 c=x:
 :a=C b=3 c=x:
 :a=A b=1 c=y:
 :a=B b=1 c=y:
 :a=C b=1 c=y:
 :a=A b=2 c=y:
 :a=B b=2 c=y:
 :a=C b=2 c=y:
 :a=A b=3 c=y:
 :a=B b=3 c=y:
 :a=C b=3 c=y:
 :a=A b=1 c=z:
 :a=B b=1 c=z:
 :a=C b=1 c=z:
 :a=A b=2 c=z:
 :a=B b=2 c=z:
 :a=C b=2 c=z:
 :a=A b=3 c=z:
 :a=B b=3 c=z:
 :a=C b=3 c=z:

> 
like image 56
jgreve Avatar answered Sep 05 '26 16:09

jgreve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!