Replace one character with another in Bash
I need to be able to do is 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.
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.
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.
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'