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

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

The easiest way to replace white spaces with (underscores) _ in bash

bashsed

提问by flazzarini

recently I had to write a little script that parsed VMs in XenServer and as the names of the VMs are mostly with white spaces in e.g Windows XP or Windows Server 2008, I had to trim those white spaces and replace them with underscores _ . I found a simple solution to do this using sed which is great tool when it comes to string manipulation.

最近我不得不编写一个小脚本来解析 XenServer 中的 VM,并且由于 VM 的名称在例如 Windows XP 或 Windows Server 2008 中大多带有空格,因此我不得不修剪这些空格并用下划线 _ 替换它们。我找到了一个简单的解决方案,可以使用 sed 来完成此操作,它是处理字符串操作的绝佳工具。

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

returns

返回

This_is_just_a_test

回答by ghostdog74

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

您可以仅使用外壳来完成,不需要trsed

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

回答by unwind

This is borderline programming, but look into using tr:

这是边界编程,但请考虑使用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.

应该做。第一次调用将空格压缩,第二次用下划线替换。您可能需要添加制表符和其他空白字符,这仅适用于空格。