Removing characters with tr

Software

In our continuing series of things you already know unless you don’t, today we’re looking at removing characters with the tr command.

tr is used to translate, or subtitute characters in a string. In its simpliest invocation:

$ printf "%s\n" "hXllo" | tr 'X' 'e'
==> hello

But what if you want to just remove X? The temptation is to supply an empty second argument:

$ printf "%s\n" "hXello" | tr 'X' ''
==> tr: empty string2

So admittedly I’d been using sed for that. This will match on every occurance of a string and replace it, which can also be a single character:

$ sed 's/X//g'

But I’ve since learned there’s a -d option:

$ tr -d 'X'

From the FreeBSD manpage(1):

-d Delete characters in string1 from the input.

Done!

Author bio and support

Me!

Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person in bios. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.