tedsedawkandvim

dedicated to sed, awk and vim

Method to Writing Regular Expressions

1. Knowing what it is you want to match and how it might appear in the text
2. Writing a pattern to describe what you want to match
3. Testing the pattern to see what it matches

The above approach to writing regular expressions is taken from the book “sed & awk (2nd Edition)” by Dale Dougherty and Arnold Robbins.  I have found that it is especially important to visit the basics when it comes to writing regular expressions and with sed, awk and vim in general.  Complex expressions are best crafted by starting at the most granular level possible and then added onto until you have something that performs as expected.  When approaching problems to solve keep this method in mind to get the results you expect.

Format List for SQL WHERE clause

This VIM Ex command is very helpful in database programming when you need to take a very large list of items and put each item in quotes and separate by a comma so that the list can simply be cut and pasted into your SQL WHERE clause.

Here is the regex:

%s/[ \t]*// | %s/[ \t]*$// | %s/.*/'\0',/g
--trim beg-----trim end------put into single quotes with comma at end

And here is why this is very useful

A list which is cut and pasted from another source may be in a form like the below …

  apples
   oranges
     bananas
  pears

*Note: If you copied a list from another source you probably have whitespace before and after your word on each line (as above) and this command will strip that out so that each word will line up in the first column.

…and you need to quickly put this list into a form that can be used in a SQL statement WHERE clause such as:

WHERE fruit in (
‘apples’,
‘oranges’,
‘bananas’,
‘pears’
)

*Note: Your last line will actually have the quotes and comma (i.e. ‘pears’,) but it is a quick and simple manual touch up required to finalize your WHERE clause.