Wednesday, February 24, 2010

Unix: Get a file's name, extension and directory name

file="/usr/local/bin/test.sh"

# get extension; everything after last '.'
ext=${file##*.}
# will return 'sh'

# everything after last '/'
basename=${file##*/}
# will return 'test.sh', similar to 'basename'

# everything before last '/'
basename=${file%/*}
# will return '/usr/local/bin', similar to 'dirname'

# back one directory
basename=${file%/*/*}
# will return '/usr/local'

No comments: