LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Server (https://www.linuxquestions.org/questions/linux-server-73/)
-   -   How to output first character of a word in capital? (https://www.linuxquestions.org/questions/linux-server-73/how-to-output-first-character-of-a-word-in-capital-758318/)

Hi_This_is_Dev 09-28-2009 04:29 PM

How to output first character of a word in capital?
 
Kindly consider:
Code:

-bash-2.05b# echo $v | tr [a-z] [A-Z]
HELLO
-bash-2.05b#

Well, I want the output in the format given below:

Code:

Hello
How can we achieve it?

In fact, I am doing this:

Code:

echo "Welcome, $USER!"
Output from the script file:

Code:

-bash-2.05b# ./welcome.sh
Welcome, root!
-bash-2.05b#

and want to display the user's name as Root instead of root or whatevever value is stored in the variable being used.

Any ideas?

neonsignal 09-28-2009 06:22 PM

If you want to use commands like tr, then you can do this:
Code:

echo $USER | head -c 1 | tr [a-z] [A-Z]; echo $USER | tail -c +2
Or you might use perl:
Code:

perl -e "print ucfirst($USER)"

PTrenholme 09-28-2009 06:23 PM

Try this:
Code:

#!/bin/bash
name=$USER
[ $# -ne 0 ] && name=$1
echo Welcome ${name^}!

(Actually, just echo Welcome ${USER^}! should do. The fluff in the code is so it can be tested.)

Hi_This_is_Dev 09-28-2009 09:01 PM

This doesn't yeild the desired result:

Code:


-bash-2.05b# echo $USER | head -c 1 | tr [a-z] [A-Z]; echo $v | tail -c +1
r
-bash-2.05b# echo $USER | head -c 1 | tr [a-z] [A-Z]
-bash-2.05b#  echo $v | tail -c +1

-bash-2.05b# v=hi
-bash-2.05b# echo $v | tail -c +1
hi
-bash-2.05b#


Hey, this does one works!
Code:

-bash-2.05b# perl -e "print ucfirst($USER)"
Root-bash-2.05b#


Thanks buddy!

Quote:

Originally Posted by neonsignal (Post 3699930)
If you want to use commands like tr, then you can do this:
Code:

echo $USER | head -c 1 | tr [a-z] [A-Z]; echo $v | tail -c +1
Or you might use perl:
Code:

perl -e "print ucfirst($USER)"


Hi_This_is_Dev 09-28-2009 09:06 PM

After running the script I get this error:

Code:

-bash-2.05b# cat cap.sh
me=$USER
[ $# -ne 0 ] && name=$1
echo Welcome ${name^}!

-bash-2.05b#
-bash-2.05b# ./cap.sh
./cap.sh: line 3: ${name^}!: bad substitution
-bash-2.05b#


Quote:

Originally Posted by PTrenholme (Post 3699933)
Try this:
Code:

#!/bin/bash
name=$USER
[ $# -ne 0 ] && name=$1
echo Welcome ${name^}!

(Actually, just echo Welcome ${USER^}! should do. The fluff in the code is so it can be tested.)




By the way, thanks to you!

David the H. 09-28-2009 09:44 PM

"${VARIABLE^}" is a new bash version 4 substitution. It doesn't exist in previous releases.

The OP's prompt shows that he's using bash 2.05, so it naturally won't work for him. But it does lead to the question as to why he's running such an old version.


All times are GMT -5. The time now is 08:15 PM.