When you are writing code for your program, you must understand that there are standard coding styles to follow. For example, "trailing whitespaces" are typically considered evil because when they get into a code repository for revision control, they can cause a lot of problems and confusion (e.g., "false diffs"). Many IDEs and text editors are capable of highlighting and automatically trimming trailing whitepsaces at the end of each line.
Here are a few ways to remove trailing whitespaces in Linux command-line environment.
A simple command line approach to remove unwanted whitespaces is via sed.
The following command deletes all spaces and tabs at the end of each line in input.java.
If there are multiple files that need trailing whitespaces removed, you can use a combination of find and sed. For example, the following command deletes trailing whitespaces in all *.java files recursively found in the current directory as well as all its sub-directories.
Vim text editor is able to highlight and trim whitespaces in a file as well.
To highlight all trailing whitespaces in a file, open the file with Vim editor and enable text highlighting by typing the following in Vim command line mode.
Then search for trailing whitespaces by typing:
This will show all trailing spaces and tabs found throughout the file.
Then to clean up all trailing whitespaces in a file with Vim, type the following Vim command.
This command means substituting all whitespace characters found at the end of the line (\s\+$) with no character.
Subscribe to Ask Xmodulo
Do you want to receive Linux related questions & answers published at Ask Xmodulo? Enter your email address below, and we will deliver our Linux Q&A straight to your email box, for free. Delivery powered by Google Feedburner.
Did you find this tutorial helpful? Then please be generous and support Xmodulo!