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'
Try this
echo "hello world" | sed 's/ /./g'
Use parameter substitution:
string=${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'
sed
. The quotes are irrelevant.
The recommended solution by shellcheck would be the following:
string="Hello World" ; echo "${string// /.}"
output: Hello.World
Success story sharing
tr
for long strings. On my systemtr
outperforms bash starting at strings with more than1000
characters. It seems like bash's time complexity is worse than linear. A small test:x="$(tr -dc 'a-z \n' </dev/urandom | head -c1M)"; time y="$(tr ' ' \\- <<< "$x")"; time z="${x// /-}"
. With a string length of 1M (=2^20)tr
took0.04s
and bash 5.0.11 took17s
. With 2Mtr
took0.07s
(expected) but bash took69s
(4 times as long for twice the string length).tr
!... Depending on available memory and hw resources... But you're right!: Depending on kind of job to do, dedicated tools stay more efficient!$'\n'