1

I tried using tr to replace a variable name in a file, and I noticed some behavior I can't figure out if the variable has a repeated character.

For example:

echo "aab" | tr 'aab' 'xyz'

gives the result 'yyz' when I was expecting xyz.

Can anyone explain what is happening here?

I'm aware that I can use other commands like sed to achieve the result I want, but I'm curious to understand what tr is doing is this situation. I've looked at the man page and haven't found any other explanation of why this would happen. Thanks

spectrum
  • 213
  • 3
  • 7
  • 1
    Considering that NONE of man pages for base tools contain any examples whatsoever, the downvote is nothing short of trolling. Why is this resource so obsessed with downvoting? – ajeh May 25 '18 at 16:01
  • 1
    @ajeh: Manual pages are concise references. They are not tutorials, and they are not intended to be used as tutorials. – AlexP May 25 '18 at 16:11
  • If you want to replace "aab" with "xyz", sed is a better tool: sed 's/aab/xyz/g' file – glenn jackman May 25 '18 at 16:42

1 Answers1

7

tr processes individual characters, not strings of characters. Its arguments are sets of characters, constituting a one-to-one mapping:

tr aab xyz

means “replace a with x, a with y, b with z”. It might help to view the two sets one above the other:

tr aab \
   xyz

If the second set is shorter than the first, it is extended by repeating the last character (by default). The sets are read in order, not applied in order; so the “ay” replacement above erases the “ax” replacement defined just prior.

Stephen Kitt
  • 434,908