hdoghmen
hdoghmen

Reputation: 3422

Remove all white space in a file and replace them with a comma using 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

Upvotes: 33

Views: 90543

Answers (4)

Kartik Arora
Kartik Arora

Reputation: 1

If the file contains n number of line and contains spaces at the start of each line, end of each line and in between. And you want to remove spaces at start and end and replace in between multiple spaces with a comma ",". And also redirect the output and save to a new file keeping the original file as it is.

Use the following command -

sed -e 's/^[ \t]*// ; s/[[:blank:]]*$// ; s/\s\+/,/g ; s/,$//' input-file-name | tee output-file-name

give paths of the input file name if not in the same directory.

or you can write all these -

"s/^[ \t]*//
s/[[:blank:]]*$//
s/\s\+/,/g ; s/,$//"

in a txt file save it. and use -f option.

so the command becomes -

sed -f commands.txt input-file-name.txt | tee output-file-name.txt

commnads.txt contains the above conditions of sed command

Upvotes: 0

user2584621
user2584621

Reputation: 2723

when converting a text file with headers and text fields with spaces I used %s/\s\{2,}/,/g

Upvotes: 0

hdoghmen
hdoghmen

Reputation: 3422

Another way to do it :

%s/\s\{1,}/,/gc

Upvotes: 6

Tim
Tim

Reputation: 14164

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

Upvotes: 85

Related Questions