Shell for fish: can stretch marks be conveniently stretched?

Is there a convenient way to strip an arbitrary extension on behalf of a file, something à la bash ${i%%.*} ? Am I sticking with my friend sed ?

+9
fish
source share
5 answers

Nope. fish have a much smaller set of functions than bash, relying on external commands:

 $ set filename foo.bar.baz $ set rootname (echo $filename | sed 's/\.[^.]*$//') $ echo $rootname foo.bar 
+8
source share

If you know the extension (e.g. _bak, regular usecase), this is probably more convenient:

 for f in (ls *_bak) mv $f (basename $f _bak) end 
+8
source share

With the string match function built into the fish, you can do

 set rootname (string match -r "(.*)\.[^\.]*\$" $filename)[2] 

Matching strings returns a list of 2 items. The first is a whole line, and the second is the first regular expression (the material inside the parentheses in the regular expression). So, we will take the second using [2].

+4
source share

The fish string command is still the canonical way to handle this. He has some really good subcommands that have not yet been shown in other answers.

split allows you to split on the right up to a maximum of 1, so you just get the latest extension.

 for f in * echo (string split -m1 -r '.' "$f")[1] end 

replace allows you to use a regular expression to trim an extension defined as an endpoint to the end of a line

 for f in * string replace -r '\.[^\.]*$' '' "$f" end 

man string for more information and some great examples.

+1
source share

You can remove the extension from the file name using the string command:

 echo (string split -r -m1 . $filename)[1] 

This will split the filename into the filename right dot and print the first element of the resulting list. If there is no dot, this list will contain one element with filename .

If you also need to remove the leading directories, merge them with the base name:

 echo (basename $filename | string split -r -m1 .)[1] 

In this example, string reads input from standard input rather than passing the file name as an argument to the command line.

0
source share

All Articles