Using regular expressions in vim to combine lines

From Notes_Wiki

Home > Regular expressions > Using regular expressions in vim to combine lines

Sometimes while copying text from tables to open-office spreadsheets the columns do not get recognized properly. When the same text is copied to a simple text-editor like 'gedit' then values of each cell may appear on separate line. It is possible to manipulating this simple text file using vim to convert it into csv format so that it can be imported in open-office spreadsheets without any problem.

To convert a text file into csv first we need to terminate lines that form a column by comma(,) or any other special character not used within text. If comma is desired and is also present in text, then text can be first enclosed in quotes and then terminated by comma. Terminating lines with comma can be done with help of regular expressions, such as:

   :%s/^\([-0-9]*\)$/\1,/gc

This expressions terminates all lines that consist only of numbers and hypen with comma. Now it is not possible to specify ranges like every second line or every third line etc. So little effort in coming up with regular expression with least false positives or false negatives is required.

Once all the columns except last one are terminated using comma(,) or some other separator we need to combine lines such that all columns appear on same line separated by separator. This can be done using regular expressions, such as:

   :%s/,$\n/,/gc

Note that a weird sequence '$\n' is used to match '\n' that ends the line instead of '\n$' as one might expect. For separators other than comma change the expression accordingly.


Home > Regular expressions > Using regular expressions in vim to combine lines