Mailinglist Archive: opensuse (2491 mails)

< Previous Next >
[opensuse] Brilliant BASH one-liners to trim whitespace using only parameter substitution
  • From: "David C. Rankin" <drankinatty@xxxxxxxxxxxxxxxxxx>
  • Date: Tue, 17 Nov 2009 22:15:25 -0600
  • Message-id: <200911172215.25893.drankinatty@xxxxxxxxxxxxxxxxxx>
Guys,

You need a break from all the 11.2 buzz. Many probably already have
this, but
for those that don't, put them in your toolbox. There is nothing new about
needing to trim whitespace from either the beginning or end of a variable, but
what is remarkable is the way the following two simple parameter substitutions
work. (They take staring at for a while)

The main benefit is there are no wastefull calls to sed (like using a
sledge
hammer to swat a fly) and there are no checks required to determine if
whitespace exists on the front or backend of a string (No more: strln=${#1};
[[ ${1:$((strlen-1))} == ' ' ]] && ...) and no more loops th count characters.
Take a look and save them where you can find them again. I ran across them on
codesnippets.joynet.com:

http://codesnippets.joyent.com/posts/show/1816

VAR="${VAR#"${VAR%%[![:space:]]*}"}" # remove leading whitespace characters
VAR="${VAR%"${VAR##*[![:space:]]}"}" # remove trailing whitespace characters

If you think about it, that is the perfect way to do it. You determine
the
exact type and number of leading or trailing whitespace and then you remove
just those characters (but all in one compact line). I have seen this
somewhere before, but I wasn't smart enough to save it. Won't happen this time
:p

--
David C. Rankin, J.D.,P.E.
Rankin Law Firm, PLLC
510 Ochiltree Street
Nacogdoches, Texas 75961
Telephone: (936) 715-9333
Facsimile: (936) 715-9339
www.rankinlawfirm.com
--
To unsubscribe, e-mail: opensuse+unsubscribe@xxxxxxxxxxxx
For additional commands, e-mail: opensuse+help@xxxxxxxxxxxx

< Previous Next >
This Thread
  • No further messages