Regular Expressions   «Prev 

Trimming Whitespace using Perl

Selective replacement Trimming whitespace

Following is an example that trims all the leading and trailing whitespace in a file:
s/^\s*(.*?)\s*$/$1/;

Notice the use of the ? character to prevent the .* from being greedy.
Without it, all the trailing spaces would end up in the subexpression.
This one also trims Perlish comments:

s/^\s*(.*?)(\s*|\s*#.*)$/$1/;

Notice that this one uses two subexpressions, but we just throw the second one away. That is because the parenthesis are necessary to bind the alternation to just the two conditions in the second subexpression.