How to Use sed to Remove Trailing newlines from File


Often you may want to use sed to remove trailing newlines from a particular file.

You can use the following syntax to do so:

sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' company_info.txt

This particular example removes all trailing newlines from the end of the file named company_info.txt.

Feel free to replace company_info.txt with the name of your own file.

The following example shows how to use this syntax in practice.

Example: Use sed to Remove Trailing newlines from File

Suppose we have a file named company_info.txt that contains the ID numbers for various employees at some company.

We can use the cat command to view the contents of this file:

Notice that there are several trailing newlines at the end of the file.

We can use the following syntax with sed to remove each of these trailing newlines:

sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' company_info.txt

The following screenshot shows how to use this syntax in practice:

sed remove trailing newlines from file

Notice that each of the trailing newlines has been removed from the end of the file.

Also note that you can use the > command to save these changes to a new file:

sed -e :a -e '/^\n*$/{$d;N;};/\n$/ba' company_info.txt > new_info.txt

The following screenshot shows how to use this syntax in practice:

sed remove trailing newlines and save results to new file

Notice that the new file named new_info.txt contains the same information as the company_info.txt file but with the trailing newlines removed from the end of the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert a Line After Match
How to Use sed to Insert Line at Specific Line Number
How to Use sed to Delete Specific Line Numbers from File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply