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
  • 56,346
  • 20
  • 107
  • 159
Rizhiy
  • 775
  • 1
  • 9
  • 31

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
  • 56,346
  • 20
  • 107
  • 159
1

You can do it like

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

it is just the order that needs to be changed.

sid-m
  • 1,504
  • 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
  • 5,324
  • 4
  • 34
  • 41
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,606
  • 15
  • 16