mootools php faith camera linux


Trim Trailing

Use sed before committing

sed -i 's/[[:space:]]*$//' ./my_file.php

The above command is useful to trim whitespace from the ends of lines in a file. The stream editor, sed is quite powerful but often misunderstood.

The first misunderstanding might be that the -i switch means case insensitivity, but that could get us in trouble. The switch means "in place", or in lay terms, "make this stream edit on the file(s) given as the second parameter, and make them immediately, in the place they exist on my filesystem."

While the command above is safe, changing the regular expression to something less benign might warrant making a copy by removing the -i switch and redirecting the output to a new file.

Regular Expression Mini-101

While regular expressions deserve their own litany of comment, let's just break down the four main parts of our above command.

A: s/[[:space:]]*$//

B: (1)/(2)/(3)/(4)

Line "A" is the regular expression from our command. Line "B" is my poor-man's diagram of the parts of the expression, which are separated by / characters.

  1. basically informs us that this is a regular expression. For now, just knowing that an "s" goes there is enough.
  2. is the "needle", or the pattern to find
  3. provides the replacement for the needle, empty in this case since we are removing the whitespace, and
  4. which is also empty in this example, is where a case insensitivity or other regular expression switch would be placed.

So in pseudo code, our sed trailing whitespace regular expression says:

  1. find and replace /
  2. spaces at the end of the line with /
  3. nothing and /
  4. no other pattern alteration like case insensitivity is required. /

Committing Code and Trailing Whitespace

Why should we remove trailing whitespace, you ask? Besides producing pure, clean code that is as fast as possible, you will join me in never wanting to spend extra time debugging. While that nirvana may never fully come to pass before Christ returns, note that trailing whitespace is mostly invisible. Developers may alter it accidentally. If using a source repository like git, we will later find that our commit shows an altered line of code, which is seemingly unaltered. And having fewer lines of code to review is always a good thing!

Last Updated: 2014-01-03 15:27:58
Creative Commons License Jay Johnston is a Zend Certified Engineer in PHP 5 LPI-ID: LPI000102450, Verfication Code: wmnnt56y2k  ... Jay Johnston is certified as LPIC-1 by the Linux Professional Institute