The power of the Unix command vi never ceases to amaze me. I have known how to search and replace easily using vi for a long time however I didn’t know how to find and replace plus insert a line break during the replace. After toying around with vi for awhile I was able to figure it out. The example below shows how to find and replace certain text while inserting a line break.
Contents of a File:
- (1,2,'title one','2009-04-20 17:55:46','description one'),(2,2,'title two','2009-04-20 18:05:54','description two'),(3,2,'title three','2009-04-20 18:23:10','description three'),(4,2,'title four','2009-04-20 19:33:42','description four'),(5,2,'title five','2009-04-20 19:45:34','description five')
The goal is to modify the text surrounding each SQL insert and add a line break which can be done using the below vi syntax. To enter this syntax open the file in vi and then type a colon (:) which will allow you to enter the below command.
vi Command:
- :%s/),(/]^M[/g
The key above is to enter the ^M by hitting (Control-V) followed by (Control-M).
File End Result:
- [1,2,'title one','2009-04-20 17:55:46','description one']
- [2,2,'title two','2009-04-20 18:05:54','description two']
- [3,2,'title three','2009-04-20 18:23:10','description three']
- [4,2,'title four','2009-04-20 19:33:42','description four']
- [5,2,'title five','2009-04-20 19:45:34','description five']
In the above example you would need to modify the begining ( and the ending ) by hand. The two books below are excellent vi and vim references and can really teach you the powers of vi. If you are new to vi or vim you will be blown away by what these commands are capable of.