Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all white space in a file and replace them with a comma using Vim

Tags:

vim

Anyone has an idea how to remove all white space and replace them with a comma , in a file using Vim ? File input example (words could be everywhere !):

C1       TEST   PROD A1    BE   T1     B1  

File output example(all words belonging to the same line are like in the example below):

C1,TEST,PROD A1,BE T1,B1  

I Found it : %s/\s\{1,}/,/gc

like image 631
hdoghmen Avatar asked Dec 07 '12 10:12

hdoghmen


People also ask

How do you replace a blank space with a comma?

Simple SED commands are: sed s/ */ /g This will replace any number of spaces with a single space. sed s/ $// This will replace any single space at the end of the line with nothing. sed s/ /,/g This will replace any single space with a single comma.

How do I remove white spaces in Linux?

s/[[:space:]]//g; – as before, the s command removes all whitespace from the text in the current pattern space.

How do I remove leading spaces in vi?

If you want to remove the leading spaces from all lines to the end of the buffer, use <G and then . repeatedly.


1 Answers

First delete the blank lines:

:g/^\s*$/d 

Then use a substitution (:s///) over each line (%) to replace all (g) continuous whitespace (\s\+) with a comma (,).

 :%s/\s\+/,/g 
like image 132
Tim Avatar answered Oct 08 '22 13:10

Tim