tedsedawkandvim

dedicated to sed, awk and vim

Execute sed / awk script in VIM

Recently I had a need to use an AWK script within VIM. It was going to be the easiest way to accomplish the task at hand – just a simple one-liner awk statement. I got pretty frusterated as I had not done this in awhile and spent a few minutes too long looking for how to do this. So for future reference here it is:

{range}!{filter}

For example: From VIM command mode (this will print the last field of each line)

:%!awk '{ print $NF }'

An important note … Remember when using sed / awk and vim to always keep your own cheaat sheet handy. Re-using a command you have done before saves an incredible amount of time and frustration. It’s a big reason I have started this site!

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.