2

I ran echo "\oo" | tr "\oo" " ", and the output is:

\

\o is not a special character, like \n, so why is the \ not converted into a space too?

0

2 Answers 2

4

\o is not a special character, like \n, so why is the \ not converted into a space too?

Because the shell and GNU tr appear to deal with unknown backslash sequences differently.

When the shell sees "\oo", it leaves the backslash as-is (I think that's the required standard behaviour). But when tr consequently gets \oo as its first argument, it interprets the \o as just o. Busybox's tr deals with this differently, this prints only spaces echo "\oo" | busybox tr "\oo" " ".

Conclusion, don't rely on undefined backslash sequences, but escape the backslashes when they are meant to be taken literally.

E.g. use echo '\oo' | tr '\\o' ' ' instead. (The single quotes protect the backslash from the shell, the second backslash escapes the other for tr.)

1

This question is essentially "how do you escape the escape '\' char?"

Answer: The same way you escape all other chars.

$ echo "\oo" | tr "\oo" " "
\ 

$ echo "\oo" | tr "\\oo" " "
\ 
 
$ echo "\oo" | tr "\\\oo" " "
 (blank output)
2
  • I see, so does the \ in echo "\oo" | tr "\oo" " " not have a meaning since you need to do \\ to replace the \ with a space? Jun 25, 2020 at 20:59
  • Yes, it has a meaning: It's the escape character. Whole wikipedia page on the topic.
    – user535733
    Jun 25, 2020 at 21:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .