Vim Tips: Replace 0px with 0

Jun
23
2009
Tagged in , , &

I like little wins. I was just looking through the CSS file for this site and noticed that - for some reason - I'd used 0px instead of   a LOT of times. Most values need numbers (10em, 10px, 10% and 10pt are all very difference sizes) however 0 is one of the few valeus which is the same in all cases (0px, 0pt, 0% and 0 are all zero!). This adds up to wasted data and bandwidth; admitedly not a lot, but still Every Little Helps!

So I fired up Vim. Initially, I just did:

%s=0px=0=g

This told Vim to do a global (%) search (s) using the = as a delimiter and find all instanced of 0px and replace with  . The g tells Vim not to stop once its found the first instance on the line. And it worked. In fact, it worked too well… Suddenly, all instances of 10px turned into 10. Bugger!

The solution ended up being a simple regular expression (God Save Regular Expressions):

%s=\([^0-9]\)0px=\10=g

I admit, it looks complicated, but essentially it's the same as the first search, however we've told it to match 0px preceded by a non numeric character (that's the [^0-9], the ^ means not and the 0-9 is a range). The reason it's in brackets is that we need to be able to reference that later on. In the replace we use \1 to tell Vim to look at the first group in the regex pattern (the bracketed non-numeric character). The unfortunately side effect of the non-numeric pattern preceding the 0px is that it also matched spaces and colons. The replace code which references this allows the matches non-numeric character to be placed back in front of the zero.

Comment Icon

2 Comments

The most recent comment was on Tue, 23rd Jun 2009, 16:11

Can do it in one step

To nail it in one step: %s=\ 0px=\ 0=gc

from an active vim user

True but...

Yours fails on…

margin:0px

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd> <img> <p>
  • You can use BBCode tags in the text. URLs will automatically be converted to links.
  • You can enable syntax highlighting of source code with the following tags: <pre>, <code>.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.

Follow Me

Recent comments

Answers 2 days ago
Replies.... 1 week ago
Or in 1 week ago
A few tweaks 1 week ago
Nice 1 week ago
Thanks a million 1 week ago
Syndicate content