more bash! regex substitution to crop trailing whitespacesy
Chris F.A. Johnson
cfaj-uVmiyxGBW52XDw4h08c5KA at public.gmane.org
Sat Dec 22 05:32:38 UTC 2007
On Tue, 18 Dec 2007, Madison Kelly wrote:
> I am almost done this darn bash script of mine (insane as it is), but I've
> got one hurdle I can't seem to get over... It *should* be the last hurdle for
> me to finish this things and start the long process of regaining some sanity.
>
> I read in key=value pairs from a file, which is easy enough. I can cut off
> preceeding white spaces just fine with:
...
> But I can't get trailing spaces cut off. The '(.*)(\s+)' pattern doesn't
> match because it's greedy and matches to the end of the string. This:
This shell function removes leading and trailing spaces (or other
character if given as the second argument):
_trim ()
{
_TRIM=$1
trim_string=${_TRIM%%[!${2:- }]*}
_TRIM=${_TRIM#"$trim_string"}
trim_string=${_TRIM##*[!${2:- }]}
_TRIM=${_TRIM%"$trim_string"}
}
var=" qwerty "
_trim "$var"
var=$_TRIM
printf ":%s:\n" "$var"
var="......uiop...."
_trim "$var" .
var=$_TRIM
printf ":%s:\n" "$var"
--
Chris F.A. Johnson, webmaster <http://woodbine-gerrard.com>
========= Do not reply to the From: address; use Reply-To: ========
Author:
Shell Scripting Recipes: A Problem-Solution Approach (2005, Apress)
--
The Toronto Linux Users Group. Meetings: http://gtalug.org/
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://gtalug.org/wiki/Mailing_lists
More information about the Legacy
mailing list