In Vim, what is the simplest way to join all lines in a file into a single line?

WindowsVim

Windows Problem Overview


I want to join all lines in a file into a single line. What is the simplest way of doing this? I've had poor luck trying to use substitution (\r\n or \n doesn't seem to get picked up correctly in the case of s/\r\n// on Windows). Using J in a range expression doesn't seem to work either (probably because the range is no longer in 'sync' after the first command is executed).

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

Windows Solutions


Solution 1 - Windows

Another way:

ggVGJ

"ggVG" visually selects all lines, and "J" joins them.

Solution 2 - Windows

Ah, I found the answer.

:1,$join

Works like a charm.

EDIT: As pointed out in the comment:

:%join   -or-    :%j

...removes the range.

Solution 3 - Windows

You can do it with 3 keystrokes starting from normal mode:

:%j
  • : enters command mode
  • % refers to all lines in the file
  • j executes the join command

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

Solution 4 - Windows

You can do it in three fewer keystrokes:

:1,$j

isn't ed grand?

Solution 5 - Windows

Cryptic way:

qqqqqJ@qq@q

(the first three q's clear the q register, the qqJ@qq records a macro to the q register that performs a Join, then calls q, and the last @q runs it.

Solution 6 - Windows

I’m surprised no one even mentioned the other way:

:%s/\n/ /

I am equally surprised that no one pointed out that the range 1,$ has a shorthand that’s written %.

(This doesn’t do the same thing as joining the lines, but depending on circumstances that may in fact be more appropriate.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJordan ParmerView Question on Stackoverflow
Solution 1 - WindowsoripView Answer on Stackoverflow
Solution 2 - WindowsJordan ParmerView Answer on Stackoverflow
Solution 3 - WindowsDimiView Answer on Stackoverflow
Solution 4 - WindowstpgouldView Answer on Stackoverflow
Solution 5 - WindowsJosh LeeView Answer on Stackoverflow
Solution 6 - WindowsAristotle PagaltzisView Answer on Stackoverflow