用(下划线)_in bash 替换空格的最简单方法

最近我不得不编写一个小脚本来解析 XenServer 中的虚拟机,由于这些虚拟机的名称在 Windows XP 或 Windows Server 2008中大多带有空格,我不得不修剪这些空格,并用下划线替换它们。我找到了一个简单的解决方案,可以使用 sed 来实现这一点,当涉及到字符串操作时,sed 是一个很好的工具。

echo "This is just a test" | sed -e 's/ /_/g'

报税表

This_is_just_a_test

还有其他办法吗?

129280 次浏览

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test