×

Search anything:

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

Internship at OpenGenus

Get this book -> Problems on Array: For Interviews and Competitive Programming

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+$' | grep -Ev '^log/'
  • Apply the previous command recursively on each file.

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+$'); 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:

  • Press ESC and then, type:
:%s/\s\+$//e
  • To save and exit the file:
: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.

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