help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Case modification


From: Greg Wooledge
Subject: Re: [Help-bash] Case modification
Date: Fri, 23 Dec 2011 15:04:58 -0500
User-agent: Mutt/1.4.2.3i

On Fri, Dec 23, 2011 at 12:12:12PM -0600, Bill Gradwohl wrote:
> I've read man bash on this and did some experimentation. I'm confused about
> how to interpret what "pattern" means. Does it take each character in
> pattern as a discrete item or does pattern get looked at as a whole.
> 
> address@hidden ~# x="hello there"; echo ${x^he}
> hello there
> Why aren't the first 2 characters upper cased?

"Pattern" in ${word^^pattern} is basically used like this:

  for each letter in word; do
    if [[ $letter = $pattern ]]; then
       uppercase it
    fi
  done

If you'll forgive this horrible mish-mash of bash and English.

> address@hidden ~# x="hello there"; echo ${x^^he}
> hello there
> Why isn't every occurrence of 'he' upper cased?

No letter can match the pattern 'he'.

> address@hidden ~# x="hello there"; echo ${x^[he]}
> Hello there
> address@hidden ~# x="hello there"; echo ${x^^[he]}
> HEllo tHErE
> This would seem to indicate that 'h' is a pattern and 'e' is a pattern and
> that 'he' is not a pattern.

In the first one, the first letter that matched the pattern was upper-cased.
In the second, all the letters that matched were upper-cased.

> The reason I'm interested in this is to see if it's possible to write a
> statement to capitalize the first letter of every word - produce 'Hello
> There'.

string='hello there'
read -ra array <<< "$string"
echo "${array[*]^?}"

The pattern '?' matches any single character, so ${word^?} will upper-case
the first letter of word.  Applying that to an array expansion makes it
operate on each array element.

You can even omit the '?' and simply use "${array[*]^}" if desired.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]