0

I am extracting the filename part from a full path as follows:

PATH=/a/b/c/foo.o  #1
BASE=${PATH##*/}   #2
BASE=${BASE/%.o/-1234.o}   #3
echo "$BASE"  

Is there a way to merge #2 and #3? Whenever I tried I got some kind of bad substitution error from bash

Jim
  • 10,120

2 Answers2

2

Yes, you can't nest the substitutions as both of them require a variable name.

You may however do it in one call to basename:

base="$( basename "$pathname" .o )-1234.o"

The second argument to basename is a suffix that will be removed from the given string.


Also note that using uppercase PATH as a variable in a shell script is a really bad idea, as this variable is used by the shell for finding external utilities.

Use lowercase variable names in scripts. This helps avoid clashes with shell variables and environment variables that the shell is using for other things.

Kusalananda
  • 333,661
  • Yes PATH was a really bad choice. But why lower case letters? To me upper case for variables seems more readable and I have read that it is the most common convention – Jim Oct 04 '17 at 08:04
  • @Jim See e.g. https://unix.stackexchange.com/questions/42847/are-there-naming-conventions-for-variables-in-shell-scripts – Kusalananda Oct 04 '17 at 08:27
0

In case if extension of the file is unknown(dynamic) - sed alternative:

p="/a/b/c/foo.txt"
p=$(sed -E 's#.*/([^/]+)(\..*)$#\1-1234\2#' <<< "$p")

echo "$p"
foo-1234.txt