Linux 通过 BASH 用下划线替换空格

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

Replace spaces with underscores via BASH

linuxbashshellunixterminal

提问by Ayush Mishra

Suppose i have a string, $str. I want $str to be edited such that all the spaces in it are replaced by underscores.

假设我有一个字符串,$str。我希望 $str 被编辑,以便其中的所有空格都被下划线替换。

Example

例子

a="hello world"

I want the final output of

我想要最终的输出

echo "$a"

to be hello_world

成为你好世界

采纳答案by William Hay

You could try the following:

您可以尝试以下操作:

str="${str// /_}"

回答by fedorqui 'SO stop harming'

With sedreading directly from a variable:

sed直接从阅读变量:

$ sed 's/ /_/g' <<< "$a"
hello_world

And to store the result you have to use the var=$(command)syntax:

要存储结果,您必须使用以下var=$(command)语法:

a=$(sed 's/ /_/g' <<< "$a")

For completeness, with awkit can be done like this:

为了完整起见,awk可以这样做:

$ a="hello my name is"
$ awk 'BEGIN{OFS="_"} {for (i=1; i<NF; i++) printf "%s%s",$i,OFS; printf "%s\n", $NF}' <<< "$a"
hello_my_name_is

回答by falsetru

$ a="hello world"
$ echo ${a// /_}
hello_world

According to bash(1):

根据 bash(1):

${parameter/pattern/string}

Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced
with string. Normally only the first match is replaced. If pattern begins with #, it must match at the beginning of the expanded value of parameter. If pattern begins with %, it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the / following pattern may be omitted. If parameter is @ or *, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.

${parameter/pattern/string}

模式替换。模式被扩展以产生一个模式,就像在路径名扩展中一样。参数被扩展,并且模式与其值的最长匹配被替换为字符串。如果模式以 / 开头,则替换所有匹配的模式
带字符串。通常只替换第一个匹配项。如果模式以# 开头,则它必须匹配参数扩展值的开头。如果模式以 % 开头,则它必须匹配参数扩展值的末尾。如果 string 为空,则删除模式的匹配项,并且可以省略 / 后面的模式。如果参数为@或*,则对每个位置参数依次进行替换操作,展开后即为结果列表。如果参数是一个带有@或*下标的数组变量,则对数组中的每个成员依次进行替换操作,展开的就是结果列表。

回答by anubhava

Pure bash:

纯猛击:

a="hello world"
echo "${a// /_}"

OR tr:

或 tr:

tr -s ' ' '_' <<< "$a"