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.
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.
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.
Latest posts by Surendra Anne (see all)
- Review: Whizlabs Practice Tests for AWS Certified Solutions Architect Professional (CSAP) - August 27, 2018
- How to use ohai/chef-shell to get node attributes - July 19, 2018
- wget download a file to a directory in Linux/Unix - June 4, 2018
- GIT: How to compare two GIT branches? - June 3, 2018
- Online training on Linux Bash shell scripting - February 8, 2018