How do I get just the filename without its path or extension to use in a command?
Answer
%:t:r
Explanation
Vim's % special character expands to the current filename and accepts a chain of colon-delimited modifiers. Each modifier transforms the path one step further, so you can compose them to extract exactly the component you need without reaching for external tools.
How it works
Common modifiers (applied left to right):
%:p— absolute path (/home/user/project/src/main.go)%:h— head: strip the last path component (/home/user/project/src)%:t— tail: keep only the filename (main.go)%:r— root: strip the extension (main)%:e— extension only (go)
These can be chained in any order:
| Expression | Result | Description |
|---|---|---|
%:t:r |
main |
filename without path or extension |
%:p:h |
/home/user/project/src |
absolute directory |
%:p:h:t |
src |
immediate parent directory name |
%:p:h:h |
/home/user/project |
grandparent directory |
Example
Compile the current Go file and run the resulting binary:
:!go build % && ./%:t:r
Open a test file for the current source file:
:e %:p:h/%:t:r_test.go
Check the parent directory with ls:
:!ls %:p:h
Tips
- All modifiers work in
:!shell commands,:e,:w, mappings, and Vim expressions viaexpand('%:t:r') - In Vim expressions use
expand():let stem = expand('%:t:r') :h filename-modifierslists all available modifiers including:s/pat/sub/for on-the-fly substitution