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

BashSed

Bash Problem Overview


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.

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

returns

This_is_just_a_test

Are there other ways to accomplish this?

Bash Solutions


Solution 1 - Bash

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

Solution 2 - Bash

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionflazzariniView Question on Stackoverflow
Solution 1 - Bashghostdog74View Answer on Stackoverflow
Solution 2 - BashunwindView Answer on Stackoverflow