vi : remove space at beginning and end of each line

This post is helpful to all vi / vim user. By this vi command user can remove space at beginning and end of each line . Today, while working I copied huge server list and pasted to new file. Now the file has lots of spaces at beginning and end of most of the lines.

By the given below two vi commands, delete space at the beginning and end of lines.

Remove space at the beginning of each line in a file

1. Open the file with vi editor

vi 

2. Press ESC key, write down below given command and hit enter

:%s/^s+

3. Save and Exit from file by pressing ESC key and typing

:wq!

Remove space at the end of each line in a file

1. Open the file with vi editor

vi 

2. Press ESC key, write down below given command and hit enter

:%s/s+$//

3. Save and Exit from file by pressing ESC key and typing

:wq!

NOTE: s finds space or tab), and + finds one or more occurrences inside the file.

1 thought on “vi : remove space at beginning and end of each line”

Comments are closed.