Note that unless your shell is fish
which doesn't support the [...]
globbing operator, you should quote those [:lower:]
, [A-Z]
, otherwise they could be expanded by the shell to the list of matching files in the current directory (or report an error if there's no match):
tr '[:lower:]' '[:upper:]'
Other notes:
- the GNU implementation of
tr
only supports single byte characters, so in a UTF-8 locale, it will only capitalise English letters without diacritics.
tr '[A-Z]' '[a-z]'
is fine, but you can also simply do tr A-Z a-z
(in POSIX compliant implementations). However, it's only guaranteed to match only on ABCDEFGHIJKLMNOPQRSTUVWXYZ
in the C/POSIX locale.
To Capitalise the first letter of every word, with the GNU implementation of sed
, you can do:
sed -E "s/[[:alnum:]_'-]+/\u&/g"
We're including '
, -
and _
but no other punctuation characters so as to turn foo-bar2baz,foo
into Foo-bar2baz,Foo
.
That works with multi-byte characters, but generally not with combining characters as most locales won't consider them as alnum
:
$ echo $'ste\u0301phane' | sed -E "s/[[:alnum:]_']+/\u&/g"
StéPhane
To consider those, you could switch to perl
, where those can be matched with \pM
:
$ echo $'ste\u0301phane chazelas' | perl -Mopen=locale -pe 's/[\w\pM'\''-]+/\u$&/g'
Stéphane Chazelas
For the sentence capitalisation, it's quite tricky, you have to capitalise the first letter found at the start of the text or after a sentence delimiter (like .
, ?
, …
…) or sentence introducer (¿
, ¡
), allowing any number of whitespace in between, but also things like (
, [
, "
, ‶
, ‷
, «
…). Depending on which language(s) you want to support, you may want to consider more.
You could do it with perl
with something like:
perl -0777 -C -pe 's/(^|[.!?…⁇⁈⁉¿¡])[\s([{"`‶‷«]*\K\p{lL}/\u$&/g'
Here assuming a UTF-8 locale and input and only covering a few of those cases.
In any case, that's not something that can be done with tr
alone as tr
transliterate every character, it can't be told to transliterate only some.