Removing characters with tr
SoftwareIn 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!