tags:

views:

500

answers:

2

Hi, 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
+2  A: 

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.

unwind
+5  A: 

you can do it will just the shell, no need tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test
ghostdog74
Or convert all non-ASCII word chars to underscores: `${str//[^a-zA-Z0-9]/_}`; either way, if you're not sticking to pure POSIX shell, then use the features available to you.
guns
there might be punctuations that are legit as well. we never know.
ghostdog74
thx for this solution exactly what I was looking for. Thanks a lot
latz