Last active
August 29, 2015 14:06
-
-
Save mburr/eac741ea7425fbea837f to your computer and use it in GitHub Desktop.
mburr / bash parse-fname
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# find latest version here: https://gist.github.com/mburr/eac741ea7425fbea837f | |
# | |
# adapted from http://stackoverflow.com/questions/965053/extract-filename-and-extension-in-bash | |
function parse-fname() | |
{ | |
# parse a filename into path, base file (without extension), and extension | |
# Which of these compenents is returned is determined by the specified option: | |
# | |
# -p - returns path (including trailing '/') | |
# -f - returns base filename without extension (this is the default) | |
# -x - returns extension (including the period) | |
# -e - synonym for -x | |
# | |
# Examples: | |
# | |
# parse-fname /some/path/test.ext --> "test" | |
# parse-fname -p /some/path/test.ext --> "/some/path/" | |
# parse-fname -f /some/path/test.ext --> "test" | |
# parse-fname -x /some/path/test.ext --> ".ext" | |
# | |
# a filename that starts with a '.' is considered to have no extension, so: | |
# | |
# parse-fname ~/.bash_profile --> ".bash_profile" | |
# parse-fname -x ~/.bash_profile --> "" | |
# | |
# Note: no canonicalization of the path or checking for existance of the file | |
# is done - this is entirely parsing based on the string value. | |
# | |
local opt="-f" # default to outputing the base filename | |
local fullfile="" | |
local arg | |
for arg; do | |
case "$arg" in | |
-f|-e|-x|-p) | |
opt="$arg" | |
;; | |
*) | |
fullfile="$arg" | |
break | |
;; | |
esac | |
done | |
local filename=$(basename "$fullfile") | |
local path="${fullfile%$filename}" | |
local extension=$([[ "$filename" = *.* ]] && echo ".${filename##*.}" || echo '') | |
# fix up the case where the filename is empty becuase the | |
# the filename looks like an extension | |
filename="${filename%.*}" | |
if [[ -z "$filename" ]]; then | |
filename="$extension" | |
extension="" | |
fi | |
case "$opt" in | |
-f) | |
echo "$filename" | |
;; | |
-e|-x) | |
echo "$extension" | |
;; | |
-p) | |
echo "$path" | |
;; | |
esac | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment