Vim Tips Wiki
Advertisement

After weeks of manually updating XML files' timestamps with the current number of milliseconds past the epoch, I finally snapped and went looking for a better way.

Rather than shell out from vim to run date +%s000 to get a current timestamp, then copy and paste that new string into a :%s/oldstamp/newstamp/ replacement, this script does it with three keystrokes and no mouse-based copy/paste.

" Add this to your ~/.vimrc file, then type '\ts' to update timestamp to current.
fun! ReplaceTimestamp()
  let tstamp = strftime("%s000")
  exe ":%s#'[0-9]\\+'#'" . tstamp . "'#g"
  echo "New time: " . tstamp
endfun
nnoremap <Leader>ts :call ReplaceTimestamp()<CR>

Comments

Thanks for the tip. Later I will insert a "new tip" header, and we will get around to discussing the tip at 201104, but here are some initial thoughts.

Relevant tips are:

The tip needs a couple of things:

  • Briefly explain what it does to someone who has never seen 'p2.timestamp' (readers shouldn't have to spend time decoding what the tip does).
  • Provide a short example (probably just one line?) of text that would be changed.
  • Quickly state what strftime('%s000') is, and mention that '%s' needs a Unix-based system (I think).

In the code, you don't need execute because substitute can replace with an expression. This should work:

  %s#<property name='p2.timestamp' value='\zs\d\+\ze'/>#\=tstamp#g

JohnBeckett 04:11, April 20, 2011 (UTC)

Per suggestions I've stripped the irrelevant bits from the example. The full version can be seen here on my blog.

--Nickboldt 14:40, April 20, 2011 (UTC)

Advertisement