VI is a tool that a natural born geek must know and use. There are many times where VI is the only editor you have available. There are also times when it is the best tool for the job.
Recently I had a data file with phone numbers that were in the NNN-NNN-NNNN format, however we needed them to be in a NNNNNNNNNN format. easy enough to just replace the hyphen/dash with a null, right? Well…it’s never that easy. There were other fields that had hyphens (last name, addresses) that I did not want to touch. I could have spent a considerable amount of time importing into Excel, fixing the data, and exporting it back in a CSV (with double quotes around each field). Instead I fixed it in a few minutes by using regular expressions and VI:
:%s/\(“[0-9][0-9][0-9]\)-\([0-9][0-9][0-9]\)-/\1\2/
Bam! It’s done. I love IT.
Here’s how to decipher that command …
\( and \) create a named area that can be referred to in the replacement string
[0-9] means any digit between 0 and 9
\1 and \2 are the named areas that were created
So we’re telling VI to find a string that starts with a quote, has three numerals, followed by a dash, followed by three digits, followed by a dash. Once found replace the original string with the first three digits (including the quote character) and the second three digits. In the process we lose the dashes.