Vim Tips: Replace 0px with 0

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
[adsense:336x280:9994499560]

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

3 Comments

The most recent comment was on Thu, 26th Jan 2012 - 05:44

Yours fails on…

margin:0px

%s/\D\zs0px/0/g which would fail on 0px in a file name for example

Add new comment

Filtered HTML

  • 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: <code>, <pre>, <bash>, <css>, <html>, <js>, <jquery>, <mysql>, <php>. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.