Shell script to convert words to Title case

Hi :slight_smile:

I have a .txt file with thousands of words.

I was wondering if i could use a simple sed or awk command to convert / replace all words in the text file to Title Case format ?

Example:

from:

this is line one
this is line two
this is line three

to desired output:

This Is Line One
This Is Line Two
This Is Line Three

Any help would be much appreciated.
Thank you!

Try:

$ awk '{for(j=1;j<=NF;j++){ $j=toupper(substr($j,1,1)) substr($j,2) }}1' file
sed -e "s/\b\(.\)/\u\1/g" file

---------- Post updated at 03:19 PM ---------- Previous update was at 03:16 PM ----------

Kindly use codetags!

Note: the use of \b and \u is GNU sed only..
It can be further reduced to:

sed 's/\b./\u&/g' file

Thank you very much. I tried them all and they all worked perfectly.

This will make it much easier now :slight_smile:

Appreciate your help!

You are welcome.

If we are picky, slightly better still would be (using GNU sed):

sed 's/\<./X\u&/g' file

Since \b means any word boundary and \< means only word boundaries at the beginning of a word, although both should work since there are no uppercase spaces or punctuation characters..

Thanks very much Scrutinizer! Appreciate that you explained the tags as well. I'm a total newbie to this stuff :slight_smile: Cheers

Hello,

One more solution, which may help too.

awk '
function getstring(var) {
num=toupper(substr($var,1,1)) substr($var,2);
print num
}
{for(i=1;i<=NF;i++){
getstring(i);
{if(i==NF-1)
ORS="\n"
else
ORS=" "}
}
}' ORS=" " filename

Output will be as follows.

This Is Line One
This Is Line Two
This Is Line Three

Thanks,
R. Singh

Hi.

In perl, with input on file data1:

perl -e 'print join(" ", map { ucfirst } split(" ", $_), "\n") while (<>);' data1

producing:

This Is Line One 
This Is Line Two 
This Is Line Three

For a system composed of:

OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution        : Debian 5.0.8 (lenny, workstation) 
perl 5.10.0

Best wishes ... cheers, drl

Some more ... possibility...

perl -ne'$x=" ";for(split//){$_=$x eq" "?uc$_:lc$_;print;$x=$_}' file