Skip to content

Instantly share code, notes, and snippets.

@leesei
Created October 20, 2013 19:45
Show Gist options
  • Save leesei/7074345 to your computer and use it in GitHub Desktop.
Save leesei/7074345 to your computer and use it in GitHub Desktop.
#bash #path_parser
#!/bin/bash
#
# path parsing function built purely from bash
# http://stackoverflow.com/a/18455930/665507
#
function path() {
SAVEIFS=$IFS; IFS="" # stash IFS for safe-keeping, etc.
[[ $# != 2 ]] && echo "usage: path <path> <dir|name|fullname|ext>" && return # demand 2 arguments
[[ $1 =~ ^(.*/)?(.+)?$ ]] && { # regex parse the path
dir=${BASH_REMATCH[1]}
file=${BASH_REMATCH[2]}
ext=$([[ $file = *.* ]] && printf %s ${file##*.} || printf '')
# edge cases for extesionless files and files like ".nesh_profile.coffee"
[[ $file == $ext ]] && fnr=$file && ext='' || fnr=${file:0:$((${#file}-${#ext}))}
case "$2" in
dir) echo "${dir%/*}"; ;;
name) echo "${fnr%.*}"; ;;
fullname) echo "${fnr%.*}.$ext"; ;;
ext) echo "$ext"; ;;
esac
}
IFS=$SAVEIFS
}
## USAGE
# SOMEPATH=/path/to.some/.random\ file.gzip
# path $SOMEPATH dir # /path/to.some
# path $SOMEPATH name # .random file
# path $SOMEPATH ext # gzip
# path $SOMEPATH fullname # .random file.gzip
# path gobbledygook # usage: -bash <path> <dir|name|fullname|ext>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment