double space 自动替换为 single

double space gets automatically replaced with single

我有一个包含以下命令的文件。

#!/bin/csh -f
echo "test  test"  //echo test [dobule space] test
set a = "test  test"  //set a = test [dobule space] test
echo $a

输出结果如下

测试[双space]测试

测试[单人space]测试

当我将值设置为 a 时,如何将双 space 替换为单个 space?

感谢任何帮助。

How does the double space get replaced with a single space when I set value to a?

不,它不会被单个 space 取代。这是因为您没有在 echo 中使用引号。使用:

echo "$a"

得到双 spaced 字符串。

Shell 默认情况下会将多个 white-space 修剪成一个 space 如果你不引用你的变量。即使这将是单身 space:

s='a     b'
echo $s
a b

但是有引号:

echo "$s"
a     b

编辑: 根据下面的评论,您可以在 csh 中执行此操作:

set QUERY = "select p.path from path p, file f where p.pathid=f.pathid and f.fileid=1234"
set dir = "`/usr/etc/venture/bin/mysql -BN -uroot -***** ****-e '$QUERY'`"
echo "$dir" 

bash 中,命令行中的任何白色 space 字符在默认情况下都被单个 space 替换,除非该值被引用。

bash man page 以非常迂回的方式讲述了这一点:

"Quoting" 部分:

Enclosing characters in single quotes preserves the literal value of each character within the quotes.

Enclosing characters in double quotes preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !

...表示白色space字符!因为,事实证明,它们是 "special":

"Word splitting" 部分:

If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words.