Swap two characters in bash with tr or similar

Viewed 734

I'm doing a bash script and I have a problem. I would like to change the position of two characters in a string.

My input is the following:

"aaaaa_eeeee"

The desired output is:

"eeeee_aaaaa"

I don't want to invert the string or anything else like that, what I need is to replace the character "a" by the "e" and the "e" by the "a". I have tried to make a echo "aaaaa_eeeee" | tr "a" "e . The first replacement is simple but the second one I don't know how to do it.

3 Answers

You can give multiple original and replacement characters to tr. Each character in the original string is replaced with the corresponding replacement character.

echo "aaaaa_eeeee" | tr "ae" "ea"

Pass Translation Sets as Arguments

To make the substitutions work in a single logical pass, you need to pass multiple characters to the tr utility. The man page for the BSD version of tr describes the use of translation sets as follows:

[T]he characters in string1 are translated into the characters in string2 where the first character in string1 is translated into the first character in string2 and so on. If string1 is longer than string2, the last character found in string2 is duplicated until string1 is exhausted.

For example:

$ tr "ae" "ea" <<< "aaaaa_eeeee"
eeeee_aaaaa

This maps a => e and e => a in a single logical pass, avoiding the issues that would result in trying to map the replacements sequentially.

This is a job for rev:

echo "aaaaa_eeeee"|rev
eeeee_aaaaa
Related