Skip to main content

Remove Trailing Spaces Using Sed

By January 12, 2018September 12th, 2022No Comments

Remove Trailing Spaces Using SedToday we look at some really practical usage of sed, the Linux stream editor. Seeing how we can remove trailing spaces using sed and keep our openLDAP LDIF files clean. In our previous video, we saw how, if there were trailing spaces at a line ending in an LDIF file the attribute would be encoded. This is, normally, undesirable so we should check for rogue spaces. This is not as easy as it sounds as a space does not easily show in a file. This is where, perhaps, sed becomes a better choice where wen an just delete spaces at the end of the line.

Sed is the stream editor and can edit the file or just the output to screen. we will use the option -i to edit the file directly:

$ sed -i 's/[[:space:]]*$//' <name-of-file.ldif>

Using the POSIX notation [[:space:]] we can search for spaces or tabs. These can be followed by any amount of white space (*) before the end of line ($). In other words we can elect all of the white space that leads directly to the end of line. We are replacing the whitespace with nothing, so we just remove training spaces using sed.