get a file's name, folder and extension
Take a path apart in a script: the folder, the name, the name without its extension, the extension.
Steps
-
file="${path##*/}"the name: /a/b/report.tar.gz → report.tar.gz
-
dir="${path%/*}"the folder: /a/b
-
ext="${file##*.}"the last extension: gz
-
base="${file%.*}"the name without it: report.tar
-
basename "$path" .gzthe same with basename, ending removed
-
dirname "$path"the folder, with dirname
Notes
- ## and %% take the longest match, # and % the shortest: ${file%%.*} gives report.
Commands used
basenamedirname
Each has a page in lore: lore basename opens it.
Related recipes
- add to the end of a fileAdd lines to a file without replacing it, also to a file only root can write.
- argument list too long"Argument list too long" from rm, cp or mv: too many files for one command line. Hand them over in batches.
- ask for input in a scriptAsk yes or no, read a password without showing it, or wait for an answer with a time limit.
- check if a file or folder existsTest in a script whether a path exists, is a file, a folder, empty or runnable.