Home > sed > sed – Convert to Title Case

sed – Convert to Title Case

I needed to ensure that text read from a file was in Title Case. Solution had to be sed 🙂

1. This is what I came up with, then I googled and found much simpler solutions that work.

echo "noRTh weST, 0" |sed 's/^\([A-Za-z]\)\([A-Za-z]\+\)/\U\1\L\2/'
North weST, 0

2. A simpler solution

echo "noRTh weST, 0" | sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g'
North West, 0

sed -e 's/.*/\L&/' - Convert all the characters to lowercase
sed -e 's/[a-z]*/\u&/g' -
Convert only the first character or each word to uppercase.

\L – Turn the replacement to lowercase until a `\U’ or `\E’ is found,
& – References the whole matched portion of the pattern space.
\u – Turn the next character to uppercase

3. Above solution will fail for the following cases

echo "nor'th we'ST, 0" | sed -e 's/.*/\L&/' -e 's/[a-z]*/\u&/g'
Nor'Th We'St, 0

echo "nor'th we'ST, 0" | sed -e 's/.*/\L&/' -e 's/[[:graph:]]*/\u&/g'
Nor'th We'st, 0

/[[:graph:]]/ – Non-blank character (excludes spaces, control characters, and similar)


Categories: sed
  1. December 16, 2013 at 11:19 am

    nice catch 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: