Is it possible to execute bash string manipulations to the filename of the current file, represented by % in external commands from within vim?


I am editing a file myfile.txt. Using :! command %, I can execute a command on myfile.txt from within vim. For instance, to copy myfile.txt to myfile.ext (simply change the extension), I can write :! cp % myfile.ext. But there is some redundancy, and I'd like to deduce myfile.ext from % (and avoid writing myfile).

In bash, if the name myfile.txt is contained in the variable $var, I can write cp $var ${var%txt}ext for instance.

Is there a way to mimick this in vim? Of course, I cannot write :! cp % ${%%txt}ext... though it is what I'd like to be able to!

1 Answer 1


You don't need to shell out to save a copy with a different extension. Try either of the following, both of which use the "root" :r modifier to strip the extension from the filename:

:w %:r.ext
:sav %:r.ext

The former will save a copy, but leave you editing the original. The latter will switch over so that you are now editing the copy.

See :h filename-modifiers for details of the many different modifiers Vim provides.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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