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.

  • "a file"? Which file? The one in the current buffer? A file somewhere in the search path? – muru Mar 8 '15 at 22:12
  • The file that the user open via `vim <file name> – iProgram Mar 8 '15 at 22:35
  • possible duplicate of How can I see the full path of the current file? – Martin Tournoij Mar 8 '15 at 22:37
  • I don't want the full path. I only want the name and extension of the file. Not the path I also want to use this in vimscript. – iProgram Mar 8 '15 at 22:40
  • Yes, both answers are actually in the linked question (specifically, CharlesL's answer)... – Martin Tournoij Mar 9 '15 at 0:32

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
  :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
  • :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. – SnoringFrog Mar 9 '15 at 20:50
  • @SnoringFrog I believe what it means is that you can't do :e:t, but :t:e is allowed, if meaningless. – muru Mar 9 '15 at 20:54
  • Oh, I see how it could be read that way. That makes sense then. – SnoringFrog Mar 9 '15 at 20:56

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.