In Vim, what is the easiest way to combine all the lines in a file into one line?

I want to combine all the lines in a file into one line. What is the easiest way to do this? I unsuccessfully tried using substitution ( \r\n or \n does not seem to be matched correctly in the case of s/\r\n// on Windows). Using J in a range expression does not work either (perhaps because the range is no longer in “sync” after the first command is executed).

I tried :1,$norm! J :1,$norm! J , but it only did half the file - that makes sense because it just joins each line once.

+53
windows vim
Dec 24 '08 at 15:51
source share
7 answers

Ah, I found the answer.

 :1,$join 

It works like a charm.

EDIT : As stated in the comment:

 :%join -or- :%j 

... removes the range.

+58
Dec 24 '08 at 15:55
source share

Another way:

 ggVGJ 

" ggVG " visually selects all the lines, and " J " concatenates them.

+126
Dec 24 '08 at 16:31
source share

You can do this with three keystrokes, starting in normal mode:

 :%j 
  • : switches to command line mode
  • % applies to all lines in a file
  • j executes the join command

Now it seems that this adds a space between the lines. I'm not sure if you want this.

+29
Apr 7 '12 at 16:11
source share

You can do this with three keystrokes:

 :1,$j 

not significant?

+13
Dec 24 '08 at 17:00
source share

Cryptic way:

 qqqqqJ@qq@q 

(the first three q clear the q register, qqJ@qq writes the macro to the q register, which makes the connection, then calls q , and the last @q starts it.

+8
Dec 24 '08 at 16:55
source share

Im surprised no one even mentioned otherwise:

 :%s/\n/ / 

I am also surprised that no one indicated that the range 1,$ has an abbreviation for % .

(This does not do the same as concatenating strings, but depending on circumstances, which may be more appropriate.)

+8
Dec 24 '08 at 22:36
source share

What if I want to join, but replace the end of the line with ";" ? I think one way is to first replace $ with; and then join, but is there an easier way?

0
Jan 30 '19 at 5:54
source share



All Articles