string 在 Bash 中用另一个字符替换一个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5928156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:05:50  来源:igfitidea点击:

Replace one character with another in Bash

stringbashreplace

提问by Brian Leishman

I need to be able to do is replace a space () with a dot (.) in a string in bash.

我需要做的是在 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.

我认为这会很简单,但我是新手,所以我无法弄清楚如何为此用途修改类似的示例。

回答by Brian Clapper

Use inline shell string replacement. Example:

使用内联 shell 字符串替换。例子:

foo="  "

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

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

See http://tldp.org/LDP/abs/html/string-manipulation.htmlfor more details.

有关更多详细信息,请参阅http://tldp.org/LDP/abs/html/string-manipulation.html

回答by aioobe

You could use tr, like this:

你可以使用tr,像这样:

tr " " .

Example:

例子:

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


From man tr:

来自man tr

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

描述
     翻译、压缩和/或删除标准输入中的字符,写入标准输出。

回答by Gilles 'SO- stop being evil'

In bash, you can do pattern replacementin 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.

在 bash 中,您可以使用构造在字符串中进行模式替换${VARIABLE//PATTERN/REPLACEMENT}。使用 just/和 not//仅替换第一次出现。该模式是一个通配符模式,就像文件 glob 一样。

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

回答by Rob

Try this

尝试这个

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

回答by Fritz G. Mehner

Use parameter substitution:

使用参数替换:

string=${string// /.}

回答by dsrdakota

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.

它用+sing 替换双引号字符串内的空格,然后用+反斜杠替换符号,然后删除/替换双引号。

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

我不得不用它来替换 Cygwin 中我的路径之一中的空格。

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