Swap two characters in bash with tr or similar
Asked Answered
G

3

5

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.

Godard answered 2/9, 2020 at 20:58 Comment(0)
J
8

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"
Jolie answered 2/9, 2020 at 21:2 Comment(0)
P
2

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.

Pechora answered 2/9, 2020 at 21:5 Comment(0)
S
0

This is a job for rev:

echo "aaaaa_eeeee"|rev
eeeee_aaaaa
Sargent answered 2/9, 2020 at 22:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.