我需要在bash中将字符串中的空格(
)替换为点号(.
)。
我认为这应该很简单,但是我是新手,无法想出如何修改类似的示例以实现此用途。
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
:
描述
将标准输入中的字符进行翻译、挤压或删除,并写入标准输出。
${VARIABLE//PATTERN/REPLACEMENT}
构造在字符串中执行pattern replacement。仅使用/
而不是//
只替换第一个出现的匹配项。该模式是通配符模式,就像文件通配符。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'
echo \"$(cygpath -u $JAVA_HOME)\"|sed 's/ /+/g'|sed 's/+/\\/g'|sed 's/\"//g'
sed
的问题。引号是无关紧要的。 - chepner
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倍)。 - Socowi$'\n'
。 - user2561747