M: On Linux, in a bash script, I have a variable called pile that has the name of a file with the full directory structure. I want just the file name, with the directory stripped away.
G: Use basename to
strip the directory part and leave just the filename:
filename=$(basename "$pile")This works regardless of how deep the directory structure is or whether the path has spaces.
M: How would I get just the file name without extension?
G: To get just the file name without the extension:
name_no_ext="${pile##*/}"
name_no_ext="${name_no_ext%.*}"Breakdown:
${pile##*/} removes the directory part (like
basename).${name_no_ext%.*} removes the extension after the last
dot.This works for simple extensions. If you're dealing with multiple
dots (e.g., file.tar.gz) and want to strip only the
last extension, this is fine. If you want to strip all
extensions, you can do:
name_no_ext="${name_no_ext%%.*}"