add newline after pattern in vim

How to Add Newline After Pattern in Vim

Vim is a popular text editor used in Linux. It provides many nifty functions and features to edit text and even write code. Some of its features allow you to bulk edit texts with just a small command. Sometimes you may need to add newline after pattern in your file. In this article, we will learn how to do this using vim editor’s bulk editing features.


How to Add Newline After Pattern in Vim

Typically users type stuff at their cursor location to make manual changes in vim. But it also allows you to do string substitutions using really compact commands. For example, in COMMAND mode, you can easily substitute strings and patterns using the %s command. Here is its syntax.

:%s/pre/cur/g
  • %: operate on the entire file
  • pre(previous pattern): pattern to be replaced
  • cur(current pattern): pattern to be added
  • g: repeat for every match on a line (default is to just replace the first)

Now if you want to add line break after a specific pattern, you can easily add line break ‘\r’ after the cur pattern above.

:%s/pre/cur\r/g

For example, if you want to add line break after ‘}’ character in file data.css, you need to go to open the file in vi editor.

$ vi data.css

Go to command mode, by hitting Esc key.

At the bottom of the screen you will see your cursor. Type/Paste the following line into it.

:%s/}/}\r/g
OR
:%s/}/\0\r/g
OR
:%s/}/&\r/g

Press enter to apply changes.

In the 2nd and 3rd command, we use special characters \0 and & which get replaced by the matched string during substitution. In the 1st command, we use the same ‘}’ character, instead.

If you exclude the ‘g’ at the end of above command, it will only replace the first instance of ‘}’

:%s/}/}\r/
OR
:%s/}/\0\r/
OR
:%s/}/&\r/

In this short article, we have learnt how to add line break after pattern in vim editor. You can replace ‘}’ in above commands with your character or substring after which you want to add line break in your file.

Also read:

How to Convert CRLF to LF in Linux
How to Store Command in Variable in Shell Script
Tar Directory Exclude Files & Folders
How to Change Color Scheme in Vim
Python Script to Check URL Status

Leave a Reply

Your email address will not be published. Required fields are marked *