将一个字符替换为另一个字符,反之亦然

Replace one character with another and vice versa in a string

我想用反斜杠“\”替换所有斜杠“/”,反之亦然。

我天真的解决方案是用 tr 做到这一点,但我需要一个占位符,我认为这不是很漂亮:

tr '/' '¢' | tr '\' '/' | tr '¢' '\'

这也只有在我的输入中从未出现“¢”时才有效,在我的情况下这很可能就足够了——但是嘿,谁知道呢?当然,很容易采用相同的想法并通过使用 sed 使其更健壮,然后将 '¢' 替换为一些任意随机字符串 - 例如 '½|#&¬_$' 或其他内容。

但我想知道是否有一些单一的 bash 命令可以实现这一点,这将使这个东西更短、更易读和更健壮。也许 sed 可以开箱即用?


请问此操作的正确名称是什么?喜欢'bidirectional replace'。如果我知道我的 google-搜索可能会更有成果。我也试过 'swap characters' 但我只找到了常规替换的东西。

你不需要中间字符,因为 tr 只遍历字符串一次,因此一个字符永远不会被替换超过一次。下面的 tr 命令应该可以做到:

tr '/\' '\/' <<< '//\ then \// and / and finally a \ in the string'

产量

\// then //\ and \ and finally a / in the string

或者,更简单地说:

tr ab ba <<< "ab ba bb aa" # yields "ba ab aa bb"

你也可以使用sed:

sed 'y#/\#\/#' <<< '//\ then \// and / and finally a \ in the string'

产量

\// then //\ and \ and finally a / in the string

来自man sed

[2addr]y/string1/string2/

Replace all occurrences of characters in string1 in the pattern space with the corresponding characters from string2. Any character other than a backslash or newline can be used instead of a slash to delimit the strings. Within string1 and string2, a backslash followed by an ``n'' is replaced by a newline character. A pair of backslashes is replaced by a literal backslash. Finally, a backslash followed by any other character (except a newline) is that literal character.

tr \\/ /\\

输入:

//fgdf\

输出:

\fgdf//

为什么是 4 个反斜杠?在 shell 中两个反斜杠组成一个反斜杠,因此 tr 接收 \//\。它有自己的反斜杠序列,因此它将两个反斜杠解释为一个反斜杠。