Many people use VIM editor for their file editing purpose in Linux. When you are coding heavily in a group project and depending on VIM editor, you will come across some issues with spaces and tabs. This will definitely irritate how the tabs will align with other IDE. The best solution is to convert your tab into space. This post is about updating your existing files and all new files with spaces when ever you press tab.

Changing tabs to space in an existing file using VI editor

In VI command mode when you are within the file, execute below regular expression to search for tabs and replace with single space.

:%s/\t/ /g

The above command will search entire file(%s) for the tab(\t) and replace with space globally(g).

For multiple files use sed to replace tabs with spaces with tabs

sed -i 's/\t/ /g' *

Here SED, which is a stream editor used to insert(-i) tabs(\t) by searching(s) for it and replacing with space globally.

All the above methods are for existing files. How about for all new files which we are going to create?

To set spaces when you type tabs use below code in your ~/.vimrc file. This is VIM editor running config file which is taken care when VI editor is used.

set tabstop=1 shiftwidth=1 expandtab

Save this ~/.vimrc file and you can start using tabs.

Set ‘tabstop’ and ‘shiftwidth’ to whatever you prefer and use ‘expandtab’.  This way you will always insert spaces.  The formatting will never be messed up when ‘tabstop’ is changed.

To get what each of these will do, use help command with in VIM to get more info on each of these.


:help tabstop

Explanation of each element can be found at VIM editor WIKI which is worth to read.

After doing this change we can do below command for existing file.


Hope this helped some one issue.