Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing one char with many chars with using tr

Tags:

bash

shell

  `echo "a~b" | tr '~' "=="`

This outputs a=b. But i wanted a==b. How can i do this with using tr?

like image 568
thetux4 Avatar asked Jun 15 '11 08:06

thetux4


People also ask

How to use tr to replace characters?

`tr` command can be used with -c option to replace those characters with the second character that don't match with the first character value. In the following example, the `tr` command is used to search those characters in the string 'bash' that don't match with the character 'b' and replace them with 'a'.

What does tr do in bash?

Translate Strings With the tr Command in Linux Bash The tr command means to translate. It is used to delete, translate and squeeze characters. It takes standard input, processes it, and writes it to standard output.

What is a tr character?

string1 and string2 are considered to be sets of characters. In its simplest form, tr translates each character in string1 into the character at the corresponding position in string2.

Which option is used with tr command for deleting characters?

The -d ( --delete ) option tells tr to delete characters specified in SET1.


3 Answers

tr just can translate/delete characters.

Try something like this:

 echo "a~b" | sed 's/~/==/g'
like image 112
Prince John Wesley Avatar answered Sep 19 '22 17:09

Prince John Wesley


You can't with tr.

Instead, use bash string manipulation ${string/substring/replacement}. Example:

str="a~b"
echo ${str/"~"/"=="}

Or use sed:

echo "a~b" | sed 's/~/==/'
like image 20
dogbane Avatar answered Sep 20 '22 17:09

dogbane


You can't; tr can only map single characters. Use sed.

like image 43
Ignacio Vazquez-Abrams Avatar answered Sep 17 '22 17:09

Ignacio Vazquez-Abrams