Replace one character with another in Bash

StringBashReplace

String Problem Overview


I need to replace a space ( ) with a dot (.) in a string in bash.

I think this would be pretty simple, but I'm new so I can't figure out how to modify a similar example for this use.

String Solutions


Solution 1 - String

Use inline shell string replacement. Example:

foo="  "

# replace first blank only
bar=${foo/ /.}

# replace all blanks
bar=${foo// /.}

See <http://tldp.org/LDP/abs/html/string-manipulation.html> for more details.

Solution 2 - String

You could use tr, like this:

tr " " .

Example:

# echo "hello world" | tr " " .
hello.world

From man tr:

> DESCRIPTION
>      Translate, squeeze, and/or delete characters from standard input, writ‐ ing to standard output.

Solution 3 - String

In bash, you can do pattern replacement in a string with the ${VARIABLE//PATTERN/REPLACEMENT} construct. Use just / and not // to replace only the first occurrence. The pattern is a wildcard pattern, like file globs.

string='foo bar qux'
one="${string/ /.}"     # sets one to 'foo.bar qux'
all="${string// /.}"    # sets all to 'foo.bar.qux'

Solution 4 - String

Try this

 echo "hello world" | sed 's/ /./g' 

Solution 5 - String

Use parameter substitution:

string=${string// /.}

Solution 6 - String

Try this for paths:

echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'

It replaces the space inside the double-quoted string with a + sing, then replaces the + sign with a backslash, then removes/replaces the double-quotes.

I had to use this to replace the spaces in one of my paths in Cygwin.

echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'

Solution 7 - String

The recommended solution by shellcheck would be the following:

string="Hello World" ; echo "${string// /.}"
output: Hello.World

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian LeishmanView Question on Stackoverflow
Solution 1 - StringBrian ClapperView Answer on Stackoverflow
Solution 2 - StringaioobeView Answer on Stackoverflow
Solution 3 - StringGilles 'SO- stop being evil'View Answer on Stackoverflow
Solution 4 - StringRobView Answer on Stackoverflow
Solution 5 - StringFritz G. MehnerView Answer on Stackoverflow
Solution 6 - StringdsrdakotaView Answer on Stackoverflow
Solution 7 - StringJuliano CostaView Answer on Stackoverflow