Is there a way to get the name and extension of a file using vimscript?
If so I would like the name and extension separately.
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityIs there a way to get the name and extension of a file using vimscript?
If so I would like the name and extension separately.
From :he filename-modifiers
:
:t Tail of the file name (last component of the name). Must
precede any :r or :e.
:r Root of the file name (the last extension removed). When
there is only an extension (file name that starts with '.',
e.g., ".vimrc"), it is not removed. Can be repeated to remove
several extensions (last one first).
:e Extension of the file name. Only makes sense when used alone.
When there is no extension the result is empty.
When there is only an extension (file name that starts with
'.'), the result is empty. Can be repeated to include more
extensions. If there are not enough extensions (but at least
one) as much as possible are included.
Examples, when the file name is "src/version.c", current dir
"/home/mool/vim":
:p /home/mool/vim/src/version.c
:t version.c
:t:r version
:e c
You can use the expand
function to expand these and obtain their values:
:let b:baz=expand('%:e')
For example:
$ vim '+ exe ":normal i" . expand("%:t") . "^M" . expand("%:e")' +wqa foo.bar; cat foo.bar
foo.bar
bar
:t
"Must precede any :r or :e," yet :e
"only makes sense when used alone". By the example, I'd side with the latter, but interesting that the docs contradict themselves there.
Mar 9, 2015 at 20:50
:e:t
, but :t:e
is allowed, if meaningless.
You can use expand()
, see :h expand()
In a script you could do this to get file-name:
let file_name = expand('%:t:r')
To get extension you could do:
let extension = expand('%:e')
The expand()
function can expand wildcards and special symbols. Here I have used %
which expands to current file-name.
after some research i found <
stands for file type in vimscript.
it seems typing :r
in vim gives the file name as well. and replacing r
with several other letters gives extensions, etc.
&filetype
/&ft
(<
is not a valid option), then it does not give the extension but rather the filetype. For some files (e.g., vim, C) these are the same. For others (e.g., python), they are not. Lastly, the :r
stuff seems reminiscent of the top answer's mention of filename modifiers…
<
is still not a valid vim variable. Perhaps you are confusing that with the encoding of < as <
, based on your web comment? Or perhaps you mean that you used %<
, which IIRC is the filename without extension.