2

How can I nest operations in bash? e.g I know that

$(basename $var)

will give me just the final part of the path and

${name%.*}

gives me everything before the extension.

How do I combine these two calls, I want to do something like:

${$(basename $var)%.*}
Alfe
  • 52,016
  • 18
  • 95
  • 150
Rizhiy
  • 660
  • 7
  • 29

4 Answers4

2

As @sid-m 's answer states, you need to change the order of the two expansions because one of them (the % stuff) can only be applied to variables (by giving their name):

echo "$(basename "${var%.*}")"

Other things to mention:

  • You should use double quotes around every expansion, otherwise you run into trouble if you have spaces in the variable values. I already did that in my answer.
  • In case you know or expect a specific file extension, basename can strip that off for you as well: basename "$var" .txt (This will print foo for foo.txt in $var.)
Alfe
  • 52,016
  • 18
  • 95
  • 150
1

You can do it like

 echo $(basename ${var%.*})

it is just the order that needs to be changed.

sid-m
  • 1,396
  • 11
  • 19
0

Assuming you want to split the file name, here is a simple pattern :

$ var=/some/folder/with/file.ext
$ echo $(basename $var) | cut -d "." -f1
file
chenchuk
  • 4,664
  • 4
  • 28
  • 39
0

If you know the file extension in advance, you can tell basename to remove it, either as a second argument or via the -s option. Both these yield the same:

basename "${var}" .extension
basename -s .extension "${var}"

If you don't know the file extension in advance, you can try to grep the proper part of the string.

### grep any non-slash followed by anything ending in dot and non-slash
grep -oP '[^/]*(?=\.[^/]*$)' <<< "${var}"
Robin479
  • 1,507
  • 12
  • 16