如何从字符串中删除空格?

Hit*_*try 51 bash shell

在ubuntu bash脚本中如何从一个变量中删除空格

字符串将是

   3918912k 
Run Code Online (Sandbox Code Playgroud)

想要删除所有空白区域.

squ*_*guy 92

这些工具sedtr将通过交换空白来为您完成此任务

sed 's/ //g'

tr -d ' '

例:

$ echo "   3918912k " | sed 's/ //g'
3918912k
Run Code Online (Sandbox Code Playgroud)

  • 完美的工作.这应该是公认的答案. (3认同)

Gil*_*not 67

尝试在shell中执行此操作:

s="  3918912k"
echo ${s//[[:blank:]]/}
Run Code Online (Sandbox Code Playgroud)

这使用参数扩展(这是一个非功能)

[[:blank:]]是一个POSIX正则表达式类(删除空格,制表符......),请参阅http://www.regular-expressions.info/posixbrackets.html

  • 参数扩展中的替换不是 POSIX。它可以在 Bash 中运行(也许还有我不知道的其他 shell),但不能在 Dash 中运行。 (2认同)
  • 这也有效:str =“$ {str // /}” (2认同)

Mic*_*lif 5

您还可以使用echo删除字符串开头或结尾处的空格,还可以在字符串中重复空格.

$ myVar="    kokor    iiij     ook      "
$ echo "$myVar"
    kokor    iiij     ook      
$ myVar=`echo $myVar`
$
$ # myVar is not set to "kokor iiij ook"
$ echo "$myVar"
kokor iiij ook
Run Code Online (Sandbox Code Playgroud)

  • 这是不可靠的:如果`myVar`包含特殊字符,如`*`,shell将使用当前目录的文件扩展它. (3认同)

gni*_*urf 5

从变量中删除所有空格的一种有趣方法是使用printf:

$ myvar='a cool variable    with   lots of   spaces in it'
$ printf -v myvar '%s' $myvar
$ echo "$myvar"
acoolvariablewithlotsofspacesinit
Run Code Online (Sandbox Code Playgroud)

事实证明,它的效率略高于myvar="${myvar// /}",但对于*字符串中可能出现的glob()来说并不安全。因此,请勿在生产代码中使用它。

如果您真的很想使用此方法并且真的担心出现问题(并且应该这样做),则可以使用set -f(完全禁用了问题):

$ ls
file1  file2
$ myvar='  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it'
$ echo "$myvar"
  a cool variable with spaces  and  oh! no! there is  a  glob  *  in it
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglobfile1file2init
$ # See the trouble? Let's fix it with set -f:
$ set -f
$ printf '%s' $myvar ; echo
acoolvariablewithspacesandoh!no!thereisaglob*init
$ # Since we like globbing, we unset the f option:
$ set +f
Run Code Online (Sandbox Code Playgroud)

我发布此答案只是因为它很有趣,而不是在实践中使用它。


Tim*_*ote 5

由于您使用bash,最快的方法是:

shopt -s extglob # Allow extended globbing
var=" lakdjsf   lkadsjf "
echo "${var//+([[:space:]])/}"
Run Code Online (Sandbox Code Playgroud)

它是最快的,因为它使用内置函数而不是启动额外的进程.

但是,如果要以符合POSIX的方式执行此操作,请使用sed:

var=" lakdjsf   lkadsjf "
echo "$var" | sed 's/[[:space:]]//g'
Run Code Online (Sandbox Code Playgroud)