Bash Script Replace Empty Spaces String

by Vivek Gite on August 14, 2006 · 6 comments

How do I remove all spaces from string using shell scripts? I've var="This is a test", and I'd like to remove all spaces.

You can sed stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is 'sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors.

Remove All Spaces

echo "This     is    a   test" | sed 's/ //g'
var="This     is    a   test"
echo $var | sed 's/ //g'
 

Replace All Spaces With * Symbol

echo "This     is    a   test" | sed 's/ /*/g'
var="This     is    a   test"
echo $var | sed 's/ /*/g'

Replace All Spaces With Bash

Bash shell supports a find and replace via substitution for string manipulation operation. The syntax is as follows:

 
${varName//Pattern/Replacement}
 

Replace all matches of Pattern with Replacement.

 
x="    This    is      a      test   "
echo "${x// /}"
### replace all spaces with * ####
echo "${x// /*}"
 

Sample outputs:

Thisisatest
****This****is******a******test***

Updated for accuracy!

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 6 comments… read them below or add one }

1 Philippe Petrinko November 14, 2010

Hi,

There is also a builtin bash shell function that you could use, which should be simplier, and quicker (it does not use an extra process like calling sed):


mystring="   Imagination   is    more   important   than   knowledge   "
echo "${mystring// /+}" # this will replace every space by a "+"
+++Imagination+++is+++more+++important+++than+++knowledge+++
echo "${mystring// /}" # this will remove every space
Imaginationismoreimportantthanknowledge

Enjoy !

Reply

2 Vivek Gite November 14, 2010

Many thanks as always :)

Reply

3 Philippe Petrinko November 14, 2010

My pleasure!
Which is reading again and again your useful and friendly WebSite, as always!
– PP

Reply

4 Philippe Petrinko June 6, 2011

So, may I know if this topic could be updated to post to introduce the other solutions I gave?
TIA,
– Philippe

Reply

5 Vivek Gite June 7, 2011

Thanks, this info has been updated.

Reply

6 Roni December 19, 2011

Hi there,
Thanks for the info, you’ve helped me in a little bash script.
Regards,
Roni.

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 10 + 11 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: