Main difference between tr (translate) to sed and awk
sed
has a y
command that is analogous to tr
:
y/string1/string2/
Replace all occurrences of characters in string1 with the corresponding characters in string2.
$ echo 'a big cat' | sed -e 'y/abc/def/'
d eig fdt
y
does not support character ranges a-z
or classes [:alpha:]
like tr
does, nor the complement modes -c
and -C
. Deletion (-d
) is possible with s//
, as is replacing runs with single characters (-s
). As in all of sed
it's fundamentally line-oriented. y
is sometimes useful in the middle of a longer sed
script, but tr
likely does a better job if that's all you're doing.
awk
has no equivalent to tr
's base functionality, though you could of course replace characters one at a time. The awk language is quite general and you can write loops and conditionals sufficient to implement any transformation you want if you're motivated enough. If you were even more motivated you could probably manage that in sed
too. The tools are not really equivalent in any sense.
Yes, tr
is a "simple" tool compared to awk
and sed
, and both awk
and sed
can easily mimic most of its basic behaviour, but neither of sed
or awk
has "tr
built in" in the sense that there is some single thing in them that exactly does all the things that tr
does.
tr
works on characters, not strings, and converts characters from one set to characters in another (as in tr 'A-Z' 'a-z'
to lowercase input). Its name is short from "translate" or "transliterate".
It does have some nice features, like being able to delete multiple consecutive characters that are the same, which may be a bit fiddly to implement with a single sed
expression.
For example,
tr -s '\n'
will squeeze all consecutive newlines from the input into single newlines.
To characterize the three tools crudely:
tr
works on characters (changes or deletes them).sed
works on lines (modifies words or other parts of lines, or inserts or deletes lines).awk
work on records with fields (by default whitespace separated fields on a line, but this may be changed by settingFS
andRS
).