tags:

views:

1716

answers:

6

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.

+22  A: 

Ah, I found the answer.

:1,$join

Works like a charm.

EDIT: As pointed out in the comment:

:%join   -or-    :%j

...removes the range.

j0rd4n
This can also be written as::%join
jleedev
Or abbreviated as :%j
Judge Maygarden
You may also want to use the gJ operation instead of j. The gJ operation joins the lines without inserting or removing any spaces.
Kris Kumler
I self-answered this because I think this is much quicker than ggVGJ and slightly more elegant.
j0rd4n
Note: %j! will join without spaces. (Add an exclamation mark.)You can't use gJ with %.
Rich
+28  A: 

Another way:

ggVGJ

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

orip
If i could upvote you I would. Examples like this show why vim is so powerful. "gg", "V", "G", "J", are all serparate commands. excellent
why can't you upvote this?
Nathan Fellman
i am not really registered with the site
and there is a rep requirement for voting.
Martinho Fernandes
+3  A: 

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.

jleedev
You probably write programs in this language for fun: http://en.wikipedia.org/wiki/Brainfuck ;)
Judge Maygarden
Of course. :-phttp://www.reddit.com/r/programming/comments/61no8/holy_shmoly_haskell_smokes_python_and_ruby_away/c02jz8x
jleedev
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
A: 

I would have done 10000P

EDIT: I meant 10000J

Joshua
What would you be pasting 10000 times?
Judge Maygarden
Err, been a bit long. I meant 10000J
Joshua
I see what your are saying, but that is kind of like watering a flower pot with a fire hose.
j0rd4n
Kudos... get er done!
ojblass
+4  A: 

You can do it in three fewer keystrokes:

:1,$j

isn't ed grand?

tpgould
:%j is 5 fewer...
Judge Maygarden
+3  A: 

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