使用内联 shell 字符串替换。例子:
foo=" "
# replace first blank only
bar=${foo/ /.}
# replace all blanks
bar=${foo// /.}
有关详细信息,请参阅 http://tldp.org/LDP/abs/html/string-manipulation.html。
您可以使用 tr
,如下所示:
tr " " .
例子:
# echo "hello world" | tr " " .
hello.world
从 man tr
:
描述 转换、压缩和/或删除标准输入中的字符,写入标准输出。
在 bash 中,您可以使用 ${VARIABLE//PATTERN/REPLACEMENT}
构造在字符串中执行 pattern replacement。仅使用 /
而不是 //
仅替换第一个匹配项。该模式是通配符模式,如文件 glob。
string='foo bar qux'
one="${string/ /.}" # sets one to 'foo.bar qux'
all="${string// /.}" # sets all to 'foo.bar.qux'
尝试这个
echo "hello world" | sed 's/ /./g'
使用参数替换:
string=${string// /.}
试试这个路径:
echo \"hello world\"|sed 's/ /+/g'|sed 's/+/\/g'|sed 's/\"//g'
它将双引号字符串中的空格替换为 +
sing,然后将 +
符号替换为反斜杠,然后删除/替换双引号。
我不得不用它来替换我在 Cygwin 中的一条路径中的空格。
echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'
sed
的问题。引号无关紧要。
不定期副业成功案例分享
tr
。在我的系统上,从超过1000
个字符的字符串开始,tr
的性能优于 bash。似乎 bash 的时间复杂度比线性的要差。一个小测试:x="$(tr -dc 'a-z \n' </dev/urandom | head -c1M)"; time y="$(tr ' ' \\- <<< "$x")"; time z="${x// /-}"
。字符串长度为 1M (=2^20) 时,tr
占用了0.04s
,而 bash 5.0.11 占用了17s
。使用 2M,tr
花费了0.07s
(预期),但 bash 花费了69s
(字符串长度的 4 倍)。tr
更快!...取决于可用内存和硬件资源...但您是对的!:根据要执行的工作类型,专用工具保持更高效!$'\n'