Zsh: Get Filename or Extension from Path

2018-01-03 ·

Get the filename from a path using :t modifier. This removes all leading pathname components, leaving just the tail. It works like basename.

#!/bin/zsh

fullpath="/etc/nginx/nginx.conf"
filename=$fullpath:t
echo $filename
nginx.conf

Or, get the path without the filename using :h modifier

#!/bin/zsh

fullpath="/etc/nginx/nginx.conf"
filename=$fullpath:h
echo $filename
/etc/nginx

Get the filename without the extension by combining two path modifiers :t and :r

#!/bin/zsh

fullpath="/etc/nginx/nginx.conf"
filename=$fullpath:t:r
echo $filename
nginx

Get just the extension by combining :t and :e path modifiers

#!/bin/zsh

fullpath="/etc/nginx/nginx.conf"
ext=$fullpath:t:e
echo $ext
conf
Copyright © 2018 All rights reserved.
Powered by Kulfon.