Remove End of Line (EOL) whitespace in Files in UNIX/ Ubuntu

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

In this article, we have demonstrated how to Remove End of Line (EOL) whitespace in Files in UNIX/ Ubuntu using grep and sed commands.

Table of contents:

  1. Remove EOL whitespace in one file
  2. Remove EOL whitespace recursively in all files
  3. Remove EOL whitespace in VI / VIM editor

Remove EOL whitespace in one file

Use the following command in the terminal to remove EOL in a single file (say code.cpp):

sed -i 's/\s*$//' code.cpp

Remove EOL whitespace recursively in all files

If you are working on a project, there will be multiple files in recursive directories and it will be tedious to remove EOL whitespace one by one for each file. We can do it at once for all files.

  • List files having End of Line whitespace and ignoring files in a specific directory such as log directory:
grep -ERl -I '\s+

                
                
                  

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.

| grep -Ev '^log/'

Type the following in the terminal. This will remove EOL from all files in a directory recursively:

cd code
for f in $(grep -ERl -I '\s+

                
                
                  

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.

); do echo $f; sed -i -e's/[[:space:]]*$//' $f; done

Remove EOL whitespace in VI / VIM editor

There might be a case when you are editing a file with vi or vim editor and before saving, you would like remove EOL whitespace if any.

Use the following command to remove EOL in a file that is currently opened in VI or VIM editor:

:%s/\s\+$//e
:wq

With this article at OpenGenus, you must have the complete idea of how to remove End of Line (EOL) whitespace in Files in UNIX/ Ubuntu.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.