如何从shell变量中删除空格?

use*_*022 17 command-line shell tr

我在命令行完成了以下操作:

$ text="name with space"
$ echo $text
name with space
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用tr -d ' '删除空格并产生以下结果:

namewithspace
Run Code Online (Sandbox Code Playgroud)

我尝试了一些事情,例如:

text=echo $text | tr -d ' '
Run Code Online (Sandbox Code Playgroud)

到目前为止没有运气所以希望你们这些优秀的人可以提供帮助!

Ste*_*n D 47

在 Bash 中,您可以使用 Bash 的内置字符串操作。在这种情况下,您可以执行以下操作:

> text="some text with spaces"
> echo "${text// /}"
sometextwithspaces
Run Code Online (Sandbox Code Playgroud)

有关字符串操作运算符的更多信息,请参阅http://tldp.org/LDP/abs/html/string-manipulation.html

但是,您的原始策略也可以使用,只是您的语法有点偏差:

> text2=$(echo $text | tr -d ' ')
> echo $text2
sometextwithspaces
Run Code Online (Sandbox Code Playgroud)


jim*_*mij 11

您根本不需要echo命令,只需使用Here String代替:

text=$(tr -d ' ' <<< "$text")
Run Code Online (Sandbox Code Playgroud)

出于好奇,我检查了这样一项微不足道的任务需要多少时间来使用不同的工具。以下是从最慢到最快排序的结果:

abc="some text with spaces"

$ time (for i in {1..1000}; do def=$(echo $abc | tr -d ' '); done)
0.76s user 1.85s system 52% cpu 4.976 total

$ time (for i in {1..1000}; do def=$(awk 'gsub(" ","")' <<< $abc); done)
1.09s user 2.69s system 88% cpu 4.255 total

$ time (for i in {1..1000}; do def=$(awk '$1=$1' OFS="" <<< $abc); done)
1.02s user 1.75s system 69% cpu 3.968 total

$ time (for i in {1..1000}; do def=$(sed 's/ //g' <<< $abc); done)
0.85s user 1.95s system 76% cpu 3.678 total

$ time (for i in {1..1000}; do def=$(tr -d ' ' <<< $abc); done)
0.73s user 2.04s system 85% cpu 3.244 total

$ time (for i in {1..1000}; do def=${abc// /}; done)
0.03s user 0.00s system 59% cpu 0.046 total
Run Code Online (Sandbox Code Playgroud)

纯shell操作绝对是最快的一点也不奇怪,但真正令人印象深刻的是它比最慢的命令快100多倍!


Ram*_*esh 5

只需修改您的文本变量,如下所示。

text=$(echo $text | tr -d ' ')
Run Code Online (Sandbox Code Playgroud)

但是,如果我们有控制字符,这可能会中断。所以,根据 Kasperd 的建议,我们可以在它周围加上双引号。所以,

text="$(echo "$text" | tr -d ' ')"
Run Code Online (Sandbox Code Playgroud)

会是更好的版本。