ninigi
ninigi

Reputation: 143

Bash, change whole word with tr

I've been looking for a solution to my problem for some time now and was unable to find it. I must use linux tr-command to change whole words. For instance, "ala, has" to "Ala, Has".
It should work like that, when I type "ala has a cat" - "Ala Has a cat".

But what I get whenever I pass it to terminal is: "ala Has a cat". Any ideas how to change whole parts of words using tr?

Also "alanna hasn't got a cat" should be changed to "Alanna Hasn't got a cat".

Upvotes: 4

Views: 8769

Answers (1)

Dimitar
Dimitar

Reputation: 4791

I am afraid that is not possible with tr, since tr can't limit the replacements. You receive ala Has a cat because first a is replaced with A and then again with a. With tr it could alternatively look like:

echo "ala has a cat" | tr -ts "'[a]' '[h]'" "'[A]' '[H]'"
AlA HAs A cAt

But as I said, tr replaces or deletes multiple characters. For more info look at the man page man tr in Linux.

However, what you want can be achieved through sed. Here is it:

echo "ala has a cat" | sed -e 's/a/A/' -e 's/h/H/'
Ala Has a cat

The -e option adds more sed-operands, sort of logical AND. Adding /g at the end would be equivalent to the tr-comand.

Upvotes: 2

Related Questions