Aug
21

How Replace Space with Newline in Vim

In vim, you can run commands to simplify tasks. One case is to replace spaces with newline, or any character.

Inside vim, go to command mode by pressing the ESC key. Then enter the following command:

:%s/\s/\r/g

This will substitute (%s) spaces (\s) with return or newline (\r) and continue the replacement until end of line (g).

This is the command to use if you need to replace newline with spaces:

:%s/\n/\s/g

This will substitute (%s) newline (\n) with space (\s) and continue the replacement until end of line (g).

You may notice that newline and return characters are used differently and not interchangeable. This is because \r means ‘carriage return’ and if ever you had one of those typewriting classes wherein you learn how to use a typewriter (not a computer!), you will know what carriage return means. Anyway, in computing, it means the same thing, to move the cursor to the beginning of the line. Although it means almost the same, newline or \n does things differently. Newline character, or ‘line feed’, instructs the cursor to move to the next line.

So how is this relevant to the vim commands above?

When the user presses the ‘Enter’ key, the equivalent command is actually ‘CR-LF’, a combination of carriage return (CR) and line feed (LF)on Windows systems. In Linux systems, the ‘Enter’ key is just ‘LF’, it is understood that you want the cursor the start at the beginning of the line.

However, in replacing \n and \r characters in vim, these two are not interchangeable. If you need to add line feed, use the CR character, \r. If you need to remove the line feed, use the LF \n character.

Related Posts

Post comment

CommentLuv Enabled

Powered by 1and1.comDomain Registrations starting at $9.98* Earn with Your BlogAdvertise @ PinoyTux

Search PinoyTux

Subscribe to Email Feeds

Enter Email Address:

Blog Lounge

Popular Posts

Recent Posts

Recent Comments

Site Stats