Total Bash noob, have been successful in doing my script by searching and looking at examples, but I need some assitance with this one, just can't figure it out.
In the Bash script I am trying to capitalize the first letter of every word in a string, ideally not changing other capitalization.
An example:
StartingVariable="NZ is the code for New Zealand"
NewVariable="NZ Is The Code For New Zealand"
If the only choice is title case then I'll go that route which would result NZ becoming Nz. Ultimately I can't figure out how to do either.
I did find a similar discussion here:
[SOLVED] 'tr' command working in console but not in bash script - Ubuntu Forums
And while it did echo the Title Case to the terminal, I couldn't figure out how to set a variable to that output.
I would really appreciate some help with this.
Thanks.
Randy
echo 'NZ is the code for New Zealand' | nawk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1'
Uh oh, I just tried this and got a message: nawk: command not found.
I didn't know it would make a difference, but I am doing this on a Mac running Snow Leopard. [whoops]
Ah, on a lark I changed nawk to awk and it works!
Fantastic, only I'm not sure how to set a new variable to that output.
VAR="NZ is the code for New Zealand"
VARCAP=${nawk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1'}
something like that I imagine.
randyharris:
Uh oh, I just tried this and got a message: nawk: command not found.
I didn't know it would make a difference, but I am doing this on a Mac running Snow Leopard. [whoops]
Ah, on a lark I changed nawk to awk and it works!
Fantastic, only I'm not sure how to set a new variable to that output.
VAR="NZ is the code for New Zealand"
VARCAP=${nawk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1'}
something like that I imagine.
#!/bin/ksh
VAR="NZ is the code for New Zealand"
VARCAP=$(echo "${VAR}" | awk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1'})
AMAZING, Thanks so much for the help!
btw - for anybody else who this may help, there was one character which needed to be removed, the "}" the second to last character.
This works beautiful for me:
#! /bin/bash
VAR="NZ is the code for New Zealand"
VARCAP=$( echo "${VAR}" | awk '{for(i=1;i<=NF;i++)sub(/./,toupper(substr($i,1,1)),$i)}1')
echo "VAR: $VAR"
echo "VARCAP: $VARCAP"