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

I recently had to write a little script that parsed virtual machines in XenServer, and since the names of the virtual machines consist mainly of white spaces, such as in Windows XP or Windows Server 2008, I had to trim these spaces and replace them with underscores _. I found a simple solution for this using sed, which is a great tool when it comes to string manipulations.

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

returns

 This_is_just_a_test 
+49
bash sed
Nov 10 '09 at 8:41
source share
2 answers

You can do this using just a shell, no tr or sed needed

 $ str="This is just a test" $ echo ${str// /_} This_is_just_a_test 
+104
Nov 10 '09 at 8:47
source share

This is front-end programming, but look at tr :

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

Gotta do it. The first call squeezes the spaces down, the second replaces the underscore. You probably need to add TAB and other space characters, this is only for spaces.

+9
Nov 10 '09 at 8:45
source share



All Articles