I'm aware of the following comparison:

if @% == "/tmp/crontab.zi5NeVPGRc"
  set nobackup
  set nowritebackup
  set noundofile
  set noswapfile

But how can I use regular expression? For example if the filename contains "crontab", then do this and that?

  • 2
    As asked, and based on the fact that you've chosen toro2k's answer, this question is actually not related to filenames at all; it could be repurposed as a general question about matching regular expressions in VimScript. On the other hand, it feels like an XY problem, and Carpetsmoker's answer does a great job of addressing what I believe you were actually trying to accomplish.
    – tommcdo
    Commented Mar 28, 2015 at 0:36
  • @tommcdo I've re-edited the question for more general purpose as suggested and toro2k answer say exactly how to write regular expression condition (as per main question). The other answer deals only with specific case and focus on autocmd and filename, but it doesn't answer the main question (how to write simple regular expression condition), that's why I've chosen toro2k answer (which is more appropriate in this case).
    – kenorb
    Commented Mar 28, 2015 at 11:05

2 Answers 2


You just have to use one of the regular expression match operators. For example, using =~# to perform a case sensitive match:

if @% =~# 'crontab'
  # the file name contains 'crontab', 
  # do this and that

Use an autocmd. Your vimrc file is executed only the first time Vim starts.

In fact, filetype.vim should already do this:

" Crontab
au BufNewFile,BufRead crontab,crontab.*,*/etc/cron.d/*      call s:StarSetf('crontab')

So you can use:

au FileType crontab setlocal backupcopy=yes

Setting nobackup is not required.

Note I'm also using setlocal, to prevent leaking this setting to other buffers, consider when you use crontab -e and then :tabe /other_file. Your :set commands will then 'leak' to this new buffer.

If you don't want to rely on the filetype for some reason:

au BufNewFile,BufRead crontab,crontab.*,*/etc/cron.d/* setlocal backupcopy=yes
  • 2
    While @toro2k answered OP's question directly, this answer solves the problem more appropriately. It's kind of an XY problem.
    – tommcdo
    Commented Mar 27, 2015 at 8:49

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.