66

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.

johnny
  • 657
  • 7
  • 18
Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
  • 1
    See also "[How to delete the '\n' of every line in a file](http://stackoverflow.com/q/6868335/254635)". – ib. Apr 08 '12 at 02:18

6 Answers6

138

Another way:

ggVGJ

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

orip
  • 73,323
  • 21
  • 116
  • 148
77

Ah, I found the answer.

:1,$join

Works like a charm.

EDIT: As pointed out in the comment:

:%join   -or-    :%j

...removes the range.

Jordan Parmer
  • 36,042
  • 30
  • 97
  • 119
40

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.

kenorb
  • 155,785
  • 88
  • 678
  • 743
Dimi
  • 401
  • 4
  • 2
17

You can do it in three fewer keystrokes:

:1,$j

isn't ed grand?

kenorb
  • 155,785
  • 88
  • 678
  • 743
tpgould
  • 1,746
  • 10
  • 10
11

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.)

Aristotle Pagaltzis
  • 112,955
  • 23
  • 98
  • 97
9

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.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • Of course. :-p http://www.reddit.com/r/programming/comments/61no8/holy_shmoly_haskell_smokes_python_and_ruby_away/c02jz8x – Josh Lee Dec 25 '08 at 07:36
  • Why would you want to clear the q register first, when you overwrite it anyway. That's like doing a bunch of no-ops to make your command longer. – Alf Jan 07 '09 at 08:25
  • 2
    @Alf : Because if you have something in the q register, you will execute that macro while recording 'J@q'. – Michele Gargiulo Feb 02 '12 at 15:01