|
|
Question : Console utility for capitalising/initialising words in string - for bash script?
|
|
Hi,
I'm trying to do a translation to a text string in a bash script, to initialise each word in a string (so we're talking console standard input/output here).
I found the 'tr' utility and tried a few things including:
echo "Simon briggs" | tr ' a-z' ' A-Z' *note the spaces*
produces "SIMON BRIGGS", when I really want "Simon Briggs"...
so it only appears to work on characters individually, when I want to check for a 'pair' of characters. This should hopefully explain what I mean at least.
Anyone have advice on a more suitable util - and perhaps some hints on the syntax required for it?
Cheers
Simon
|
Answer : Console utility for capitalising/initialising words in string - for bash script?
|
|
You probably want to use perl (specifically - "perl -e") ? It's considerably more powerful, and understands all alphabets in all languages, instead of just English using ASCII
echo 'fred nerk' | perl -e 'undef $/;$a=<>; $a=~s/\b(.)/\u$1/sg; print $a';
What the above does is...
undef $/; # treats line breaks like spaces, instead of input terminators $a=<>; # Gets the input $a=~s/\b(.)/\u$1/sg; # Does the conversion* print $a; # Outputs it
Here's the regular expression explanation:-
$a # This has out input =~ # Tells perl to convert it using the following regexp s/ # Says we want to substiture stuff \b(.) # Matches any "word break" and grabs the next character / # End of the match separator \u$1 # replaces what we matched with the uppercase version of it ($1 is the variable from the earlier matching brackets) /sg; # "s" means treat line breaks like spaces, "g" means do everything (not just the 1st)
|
|
|
|
|