Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

sed

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?

like image 267
flazzarini Avatar asked Nov 10 '09 08:11

flazzarini


People also ask

How do I remove white space in bash?

Note that tr -d "[:space:]" removes both horizontal and vertical whitespace characters (=newlines). To remove just horizontal whitespace characters simply use tr -d " " .

How do I replace a space in bash?

Use sub(/\^/, " ", str) to replace with space, and gsub(/\^/, " ", str) to replace every occurrence.

How do I change white space in Linux?

Simple SED commands are: sed s/ */ /g This will replace any number of spaces with a single space. sed s/ $// This will replace any single space at the end of the line with nothing.


1 Answers

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 
like image 61
ghostdog74 Avatar answered Sep 21 '22 14:09

ghostdog74