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)%.*}
2
  • 1
    It appears that none of the answers addresses the "real" question, i.e. is nested variable expansion possible? Without using a command line tool like basename. Commented Dec 5, 2018 at 15:37
  • Here an answer (though not the accepted one): stackoverflow.com/a/6724305/1172302 Commented Dec 5, 2018 at 15:38

4 Answers 4

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.)
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it like

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

it is just the order that needs to be changed.

2 Comments

Thanks, that worked. Can you explain the logic why it has to be that way around?
The echo is unnecessary; basename "${var%.*}" does the same thing..
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

Comments

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}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.