string bash:如何在字符串中添加空格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37367841/
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-08 16:32:21  来源:igfitidea点击:

bash: How to add space in string?

stringbashspaces

提问by Marta Koprivnik

I have a string like this:

我有一个这样的字符串:

string="aaa-bbb"

But I want to add space before char '-', so I want this:

但我想在字符'-'之前添加空格,所以我想要这个:

aaa -bbb

I tried a lot of things, but I can't add space there. I tried with echo $string | tr '-' ' -', and some other stuff, but it didn't work...

我尝试了很多东西,但我无法在那里添加空间。我尝试过echo $string | tr '-' ' -',以及其他一些东西,但没有奏效......

I have Linux Mint: GNU bash, version 4.3.8(1)

我有 Linux Mint:GNU bash,版本 4.3.8(1)

回答by Jeff Bowman

No need to call sed, use string substitutionnative in BASH:

无需调用sed,在 BASH 中使用原生字符串替换

$ foo="abc-def-ghi"
$ echo "${foo//-/ -}"
abc -def -ghi

Note the two slashesafter the variable name: the first slash replaces the first occurrence, where two slashes replace every occurrence.

注意变量名后面的两个斜杠:第一个斜杠替换第一次出现,两个斜杠替换每次出现。

回答by Jay jargot

Give a try to this:

试试这个:

printf "%s\n" "${string}" | sed 's/-/ -/g'

It looks for -and replace it with -(space hyphen)

它查找-并替换为-(空格连字符)

回答by webb

trcan only substitute one character at a time. what you're looking for is sed:

tr一次只能替换一个字符。你要找的是sed

echo "$string" | sed 's/-/ -/'

echo "$string" | sed 's/-/ -/'

回答by Stephen Quan

Bash has builtin string substitution.

Bash 具有内置的字符串替换功能。

result="${string/-/ -}"
echo "$result"

Alternatively you can use sed:

或者,您可以使用sed

result=$(echo "$string" | sed 's/-/ -/')
echo "$result"

回答by Stephen Quan

You are asking the shell to echo an un-quoted variable $string.
When that happens, spaces inside variables are used to split the string:

您要求 shell 回显一个未加引号的变量$string
发生这种情况时,变量内的空格用于拆分字符串:

$ string="a -b -c"
$ printf '<%s>\n' $string
<a>
<-b>
<-c>

The variable does contain the spaces, just that you are not seeing it correctly. Quote your expansions

该变量确实包含空格,只是您没有正确看到它。 引用您的扩展

$ printf '<%s>\n' "$string"
<a -b -c>


To get your variable changed from -to -there are many solutions:

要将变量从 更改--有很多解决方案:

sed: string="$(echo "$string" | sed 's/-/ -/g')"; echo "$string"
bash: string="${string//-/ -}; echo "$string"

sed: string="$(echo "$string" | sed 's/-/ -/g')"; echo "$string"
bash:string="${string//-/ -}; echo "$string"